<?php

namespace App\Libs\wrapper;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Jobs\SavePdfController;
use App\Models\BaseModel;
use App\Models\Common\Constant;
use App\Models\Datawhole;
use App\Models\InventoryModel;
use App\Models\ResourceModel\TasksExamine;
use App\Models\ResourceModel\TasksNode;
use App\Models\ResourceModel\TasksSon;
use App\Models\TaskModel;
use App\Models\TaskClassModule;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;
use App\Models\ResourceModel\OrganizesMemberModel;
use App\Models\ResourceModel\OrganizesModel;
use League\Flysystem\Exception;

class Task extends Comm
{
//////////////////////////////////////////////// 任务
////////////////////// 新增任务页面
    protected $organizesModel;
    protected $organizesMemberModel;
    protected $taskModel;
    protected $taskExamineModel;
    protected $taskNodeModel;
    protected $taskSonModel;

    public function __construct(){
        $this->organizesModel = new OrganizesModel();
        $this->organizesMemberModel = new OrganizesMemberModel();
        $this->taskModel = new TaskModel();

        $this->taskSonModel = new TasksSon();
        $this->taskExamineModel = new TasksExamine();
        $this->taskNodeModel = new TasksNode();

    }

    public function redis_tiding($tiding_id, $user_fs, $user_js, $title, $content, $task_id, $object_type, $type)
    {
        $time = date('Y-m-d H:i:s');
        $redis['Id'] = $tiding_id;
        $redis['user_fs'] = $user_fs;
        $redis['user_js'] = $user_js;
        $redis['title'] = $title;
        $redis['content'] = $content;
        $redis['object_id'] = $task_id;
        $redis['object_type'] = $object_type;
        $redis['type'] = $type;
        $redis['create_time'] = $time;
        $redis['is_read'] = 1;
        Redis::Hset('tiding:' . $user_js, $tiding_id, json_encode($redis, JSON_UNESCAPED_UNICODE));
        Redis::Lpush('tiding_key:' . $user_js, $tiding_id);
    }

    /**
     * 部门用户
     */
    public function department_user()
    {
        //查找部门表
        $department_sql = "select `Id`,`name` from `organizes` where `type`=1 and `state`=1";
        $department = json_decode(json_encode(db::select($department_sql)), true);

        //查找小组表
        $group = DB::table('organizes')->where('type',2)->where('state',1)->get();
        $group = json_decode(json_encode($group), true);
        foreach ($group as $g){
            $groupArr[$g['Id']] = $g['fid'];
        }
        //查找部门用户
        $member_sql = "select om.organize_id,om.user_id,u.account
                            from organizes_member om
                            left join users u on u.Id=om.user_id
                            where u.state=1";
        $member = json_decode(json_encode(db::select($member_sql)), true);
        foreach ($member as $k=>$m){
            if(isset($groupArr[$m['organize_id']])){
                $member[$k]['organize_id'] = $groupArr[$m['organize_id']];
            }
        }
        $array = array();
        $children = array();
        foreach ($department as $depart_key => $depart_value) {
            $array[$depart_key]['value'] = $depart_value['Id'];
            $array[$depart_key]['label'] = $depart_value['name'];
            $i = 0;
            foreach ($member as $key => $value) {
                if ($depart_value['Id'] == $value['organize_id']) {
                    $array[$depart_key]['children'][$i]['value'] = $value['user_id'];
                    $array[$depart_key]['children'][$i]['label'] = $value['account'];
                    $i++;
                }

            }
        }
//        var_dump($array);die;
        $return['list'] = $array;
        return $return;
    }

    /**
     * @Desc:获取部门人员列表
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/2/28 18:26
     */
    public function getDepartmentList($params = [])
    {
        $return = $this->_filterDepartmentList($params);

        return $return;
    }

    private function _filterDepartmentList($params)
    {
        $organizeModel = $this->organizesModel::query()->where('state', 1);
        // 查询组织人员绑定
        $organizeMemberModel = $this->organizesMemberModel::query()
            ->join('users as u', 'u.Id', '=', 'organizes_member.user_id')
            ->get()
            ->toArray();

        // 过滤登录人
        if (isset($params['user_id']) && !empty($params['user_id'])){
            $orgIds = $this->organizesMemberModel::query()->where('user_id', $params['user_id'])->select('organize_id')->get()->toArray();
            $organizeModel->whereIn('Id', $orgIds);
        }
        // 过滤上级id
        if (isset($params['fid']) && !empty($params['fid'])) {
            $organizeModel->whereIn('fid', (array)$params['fid']);
        }
        // 过滤类型 1.部门、2.小组
        if (isset($params['type']) && !empty($params['type'])) {
            $organizeModel->where('type', $params['type']);
        }
        // 过滤名称
        if (isset($params['name']) && !empty($params['name'])) {
            $organizeModel->where('name', 'like', '%'.$params['name'].'%');
        }
        // 过滤组织id
        if (isset($params['org_id']) && !empty($params['org_id'])) {
            $organizeModel->whereIn('Id', (array)$params['org_id']);
        }
        // 获取查询总数
        $count = $organizeModel->count();
        $list = $organizeModel->get()->toArray();
        foreach ($list as &$item) {
            foreach ($organizeMemberModel as $_item){
                if ($item['Id'] == $_item['organize_id']){
                    $item['user'][] = [
                        'Id' => $_item['user_id'],
                        'name' => $_item['account']
                    ];
                }
            }
        }
        // 过滤分页
        $limit = $params['limit'] ?? 30;
        $page = $params['page'] ?? 1;
        $pageNum = $page <=1 ? 0 : $limit*($page-1);
        $organizeModel->offset($pageNum)->limit($limit);

//        $list = $this->_getOrgnizesTree($list, 0);

        return ['count' => $count, 'list' => $list];
    }

    public function _getOrgnizesTree($data, $fid = 0)
    {
        $tree = [];
        foreach($data as $k => $v)
        {
            if($v['fid'] == $fid)
            {
                $v['child'] = $this->_getOrgnizesTree($data, $v['Id']);
                $tree[] = $v;
                unset($data[$k]);
            }
        }

        return $tree;
    }

    /**
     * 新增任务
     * @parma name 任务名称
     * @param user_fz 负责人
     * @param file_fj 附件
     * @param desc 任务描述
     * @param examine 审核人  数组
     * @param user_cs 抄送人  数组
     * @param node 节点、节点任务   数组
     *              name 节点名称
     *              node_task_data 节点任务     数组
     *                      user_id 执行人
     *                      day 预计完成天数
     *                      task 任务
     * @logic 新增任务，验证唯一 --> 新增任务审核 --> 新增节点、节点任务
     */
    public function task_add($data)
    {
        try {
            db::beginTransaction();    //开启事务


//            if (isset($data['task_id']) && !empty($data['task_id']) && isset($data['request_id']) && !empty($data['request_id'])){

            // 判断是否为重新发布任务
            if (isset($data['task_id']) && !empty($data['task_id']) && isset($data['is_update']) && !empty($data['is_update'])){
                // 删除原有任务数据
                $this->taskModel::query()
                    ->where('Id', $data['task_id'])
                    ->delete();
                $this->taskSonModel::query()
                    ->where('task_id', $data['task_id'])
                    ->delete();
                DB::table('tasks_node')->where('task_id', $data['task_id'])->delete();
                DB::table('tasks_examine')->where('task_id', $data['task_id'])->delete();
                DB::table('tasks_news')->where('task_id', $data['task_id'])->delete();
            }
            //新增任务，验证唯一 --> 新增任务审核 --> 新增节点、节点任务
            //// 新增任务
            // 验证唯一
            $sql = "select `Id`
					from `tasks`
					where `name` = '{$data['name']}'";
            if (isset($data['task_id']) && !empty($data['task_id']) && isset($data['request_id']) && !empty($data['request_id'])) {
                $sql = "select `Id`
					from `tasks`
					where `name` = '{$data['name']}' and `Id` <> '{$data['task_id']}'";
            }
            $task_find = json_decode(json_encode(db::select($sql)), true);
            if (!empty($task_find)) {
                return '任务名称已被使用，不能重复！';
            }

            //当前时间
            $time = time();
            $time_now = date('Y-m-d H:i:s', $time);

            // 新增任务

            $arr = array();
            $arr['name'] = $data['name'];
            $arr['user_fz'] = $data['user_fz'];
            $arr['user_cj'] = isset($data['user_cj']) ? $data['user_cj'] : '';
            $arr['file_fj'] = isset($data['file_fj']) ? json_encode($data['file_fj']) : '';
            $arr['img'] = isset($data['img']) ? json_encode($data['img']) : '';
            $arr['user_cs'] = empty($data['user_cs']) ? '' : implode(',', $data['user_cs']);
            $arr['desc'] = isset($data['desc']) ? $data['desc'] : '';
            $arr['state'] = isset($data['examine']) ? 1 : 3;
            $arr['shop_id'] = isset($data['shop_id']) ? $data['shop_id'] : '';
            $arr['audit_method'] = $data['audit_method'];
            $arr['type'] = 1;
            $arr['create_time'] = $time_now;
            if (isset($data['class_id'])) {
                $arr['class_id'] = $data['class_id'];
            }else{
                db::rollback();// 回调
                return '请选择任务分类';
            }
            $task_class = DB::table('task_class')->where('id',$arr['class_id'])->select('is_task')->first();
            if (isset($data['ext'])) {
                foreach ($data['ext'] as $extKey=>$extVal){
                    if($extVal==NULL) {
                        $data['ext'][$extKey]='';
                    }
                }
                if(isset($data['ext']['asin'])){
                    $data['ext']['asin'] = trim($data['ext']['asin']);
                }
                $arr['ext'] = json_encode($data['ext'], JSON_UNESCAPED_UNICODE);
                if($task_class->is_task==2){
                    if (in_array($data['class_id'], [2,3,4])) {
                        if(isset($data['ext']['request_id']) && !empty($data['ext']['request_id'])){
//                            $update_request = Db::table('amazon_buhuo_request')->where('id', $data['ext']['request_id'])->update(['request_status' => 3]);
                            if (!isset($data['ext']['start_time'])) {
                                db::rollback();// 回调
                                return '请选择预计销售开始日期';
                            }
                            if (!isset($data['ext']['end_time'])) {
                                db::rollback();// 回调
                                return '请选择预计销售结束日期';
                            }
                            //云仓补货计划则加入出库单队列
                            if($data['class_id']==2) {
                                $params['method'] = 'stockout.create';
                                $params['order_no'] = $data['ext']['request_id'];
                                $params['type'] = 'B2BCK';
                                $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                                try {
                                    $cloud::outhouseJob($params);
                                    Redis::Lpush('cloud_outRequest', $data['ext']['request_id']);
                                } catch (\Exception $e) {
                                    Redis::Lpush('out_house_fail', $data['ext']['request_id']);
                                }
                            }
                        }else{
                            db::rollback();// 回调
                            return '未获取到计划id';
                        }
                    }
                    if (in_array($data['class_id'], [127])) {
                        if(isset($data['ext']['request_id']) && !empty($data['ext']['request_id'])){
                            $update_request = Db::table('amazon_buhuo_request')->where('id', $data['ext']['request_id'])->update(['request_status' => 3]);

                            if (!isset($data['ext']['start_time'])) {
                                db::rollback();// 回调
                                return '请选择预计销售开始日期';
                            }
                            if (!isset($data['ext']['end_time'])) {
                                db::rollback();// 回调
                                return '请选择预计销售结束日期';
                            }
                            if (!isset($data['ext']['warehouse_id'])) {
                                db::rollback();// 回调
                                return '未给定发货仓库标识！';
                            }
                            if (!isset($data['ext']['warehouse_name'])) {
                                db::rollback();// 回调
                                return '未给定发货仓库名称！';
                            }
                        }else{
                            db::rollback();// 回调
                            return '未获取到计划id';
                        }
                    }

                    if (in_array($data['class_id'], [124])) {
                        if (isset($data['ext']['request_id']) && !empty($data['ext']['request_id'])) {
                            $update_request = Db::table('amazon_buhuo_request')->where('id', $data['ext']['request_id'])->update(['request_status' => 3]);
                            if (!$update_request){
                                db::rollback();// 回调
                                return '补货计划状态更新失败！';
                            }
                            if (!isset($data['ext']['start_time'])) {
                                db::rollback();// 回调
                                return '请选择预计销售开始日期';
                            }
                            if (!isset($data['ext']['end_time'])) {
                                db::rollback();// 回调
                                return '请选择预计销售结束日期';
                            }
                        }else{
                            db::rollback();// 回调
                            return '未获取到计划id';
                        }
                    }

                    if(isset($data['ext']['order_id'])){
                        if(!empty($data['ext']['order_id'])) {
                            $update_order = Db::table('amazon_place_order_task')->where('id', $data['ext']['order_id'])->update(['status' => 1]);
                        }else{
                            db::rollback();// 回调
                            return '未获取到计划id';
                        }
                    }
                    if(isset($data['ext']['transfers_id'])){
                        if(!empty($data['ext']['transfers_id'])) {
                            $update_order = Db::table('goods_transfers')->where('order_no', $data['ext']['transfers_id'])
                                ->update(['is_push' => 2, 'status' => 3,'push_time'=>date('Y-m-d H:i:s')]);
                        }else{
                            db::rollback();// 回调
                            return '未获取到计划id';
                        }
                    }

                    // 下单合同审核任务
                    if (isset($data['ext']['contract_id'])){
                        if(!empty($data['ext']['contract_id'])) {
                            if (!isset($data['ext']['contract_no']) || empty($data['ext']['contract_no'])) {
                                throw new \Exception('请设置合同号！');
                            }
                            if (!isset($data['ext']['contract_link']) || empty($data['ext']['contract_link'])) {
                                throw new \Exception('请设置合同详情跳转链接！');
                            }
                            $contractMdl = Db::table('cloudhouse_contract_total')->where('contract_no', $data['ext']['contract_no'])->first();
                            $baseModel = new BaseModel();
                            $data['ext']['total_count'] = $contractMdl->total_count;
                            $data['ext']['total_price'] = $baseModel->floorDecimal($contractMdl->total_price);
                            $data['ext']['report_date'] = $contractMdl->report_date;
                            Db::table('cloudhouse_contract_total')->where('contract_no', $data['ext']['contract_no'])->update(['contract_status' => 1, 'pursubmit_date' => microtime(true)]);
                        }else{
                            db::rollback();// 回调
                            return '未获取到计划id';
                        }
                    }

                    if (isset($data['ext']['bill_id'])) {
                        if(!empty($data['ext']['bill_id'])) {
                            if (!isset($data['ext']['bill_no']) || empty($data['ext']['bill_no'])) {
                                throw new \Exception('请设置票据号！');
                            }
                            if (!isset($data['ext']['detail_url']) || empty($data['ext']['detail_url'])) {
                                throw new \Exception('请设置票据详情跳转链接！');
                            }
                            $billMdl = db::table('financial_bill')->where('bill_no', $data['ext']['bill_no'])->first();
                            if (!empty($billMdl)) {
                                $billMdl = db::table('financial_bill')->where('bill_no', $data['ext']['bill_no'])->update(['status' => 1, 'updated_at' => date('Y-m-d H:i:s')]);
                                if (!$billMdl) {
                                    throw new \Exception('票据状态修改失败，无法生成任务！');
                                }
                            }
                        }else{
                            db::rollback();// 回调
                            return '未获取到计划id';
                        }
                    }

                    if ($data['class_id'] == 93){
                        if (!isset($data['ext']['quotation_id']) || empty($data['ext']['quotation_id'])){
                            throw new \Exception('未给定需求标识！');
                        }
                        if (!isset($data['ext']['spu']) || empty($data['ext']['spu'])){
                            throw new \Exception('未给定spu！');
                        }
                        if (!isset($data['ext']['detail_url']) || empty($data['ext']['detail_url'])){
                            throw new \Exception('未给定跳转链接！');
                        }
                        $model = db::table('self_spu_quotation_demand')->where('id', $data['ext']['quotation_id'])->first();
                        if (empty($model)){
                            throw new \Exception('未查到报价需求数据！');
                        }
//                        $spuModel = new Spu();
//                        $result = $spuModel->spuQuotation(['quotation_id' => $model->id, 'user_id' => $data['user_fz']]);
                        $num = $model->num + 1;
                        if ($num > 3){
                            throw new \Exception('报价发布不可超过3次！');
                        }
                        $update = db::table('self_spu_quotation_demand')
                            ->where('id', $model->id)
                            ->update([
                                'num' => $num,
                                'status' => 1
                            ]);
                        $logMdl = db::table('self_spu_quotation_log')
                            ->where('sort', '<', $num)
                            ->where('quotation_id', $model->id)
                            ->update(['is_update' => 0]);
                        if (empty($update)){
                            throw new \Exception('报价发布次数未更新成功！');
                        }
                    }

                    if ($data['class_id'] == 95){
                        if (!isset($data['ext']['proofing_id']) || empty($data['ext']['proofing_id'])){
                            throw new \Exception('未给定需求标识！');
                        }
                        if (!isset($data['ext']['spu']) || empty($data['ext']['spu'])){
                            throw new \Exception('未给定spu！');
                        }
                        if (!isset($data['ext']['detail_url']) || empty($data['ext']['detail_url'])){
                            throw new \Exception('未给定跳转链接！');
                        }
                        $model = db::table('self_spu_proofing_demand')->where('id', $data['ext']['proofing_id'])->first();
                        if (empty($model)){
                            throw new \Exception('未查到打样需求数据！');
                        }
//                        $spuModel = new Spu();
//                        $result = $spuModel->spuProofing(['proofing_id' => $model->id, 'user_id' => $data['user_fz']]);
                        $num = $model->num + 1;
                        if ($num > 3){
                            throw new \Exception('打样发布不可超过3次！');
                        }
                        $update = db::table('self_spu_proofing_demand')
                            ->where('id', $model->id)
                            ->update([
                                'num' => $num,
                                'status' => 1
                            ]);
                        $logMdl = db::table('self_spu_proofing_log')
                            ->where('sort', '<', $num)
                            ->where('proofing_id', $model->id)
                            ->update(['is_update' => 0]);
                        if (empty($update)){
                            throw new \Exception('打样发布次数未更新成功！');
                        }
                    }
                }


                /*if(!isset($data['ext']['activity_type'])){
                    return '请选择活动类型';
                }
                if(!isset($data['ext']['is_lock'])){
                    return '请选择是否锁库存';
                }
                if(!isset($data['ext']['is_allocation'])){
                    return '请选择调拨';
                }
                if(!isset($data['ext']['is_sku_close'])){
                    return '请选择自发货SKU是否关闭';
                }
                if(!isset($data['ext']['superposition_coupon'])){
                    return '请选择叠加coupon';
                }
                if(!isset($data['ext']['is_overlap'])){
                    return '请选择是否折扣重叠';
                }
                if(!isset($data['ext']['asin'])){
                    return '请填写asin';
                }
                if(!isset($data['ext']['start_time'])){
                    return '请选择开始时间';
                }
                if(!isset($data['ext']['end_time'])){
                    return '请选择结束时间';
                }*/


            }

            $task_add = db::table('tasks')->insertGetId($arr);

            if (!$task_add) {
                db::rollback();// 回调
                return '新增任务失败--tasks表';
            }

            //// 新增节点、节点任务
            if(!empty($data['node'])){
                foreach ($data['node'] as $k => $v) {
                    // 新增节点
                    $arr = array();
                    $arr['task_id'] = $task_add;
                    $arr['name'] = $v['name'];
                    if (isset($v['circulation'])) {
                        $arr['circulation'] = $v['circulation'];
                    }
                    $node_add = db::table('tasks_node')->insertGetId($arr);
                    if (!$node_add) {
                        db::rollback();// 回调
                        return '新增任务节点失败--tasks_node表';
                    }
                    // 节点任务
                    $insert = "";
                    if(isset($v['node_task_data'])){
                        foreach ($v['node_task_data'] as $k1 => $v1) {
                            if($v1['user_id']==0){
                                $knum = $k+1;
                                db::rollback();// 回调
                                return '新增失败，第'.$knum.'节点执行人为空';
                            }
                            $insert .= ",({$task_add}, {$node_add}, '{$v1['task']}', {$v1['user_id']}, {$v1['day_yj']}, now())";
                        }
                        $insert = substr($insert, 1);
                        $sql = "insert into tasks_son(`task_id`, `tasks_node_id`, `task`, `user_id`, `day_yj`, `create_time`) values {$insert}";
                        $tasks_son_add = db::insert($sql);
//            var_dump($sql);
                        if (!$tasks_son_add) {
                            db::rollback();// 回调
                            return '新增节点任务失败--tasks_son表';
                        }
                    }
                }
            }

            //// 新增任务审核
            if (!empty($data['examine'])) {
                $insert = "";
//            $insert2 = "";
                $content1 = "任务：{$data['name']} ，需要您审核，情尽快处理！";
                if (is_array($data['examine'])){
                    $data['examine'] = array_values(array_unique($data['examine']));
                }
                foreach ($data['examine'] as $k => $v) {
                    if (empty($insert) || $data['audit_method'] == 2) {
                        $insert .= "({$task_add}, {$v}, 2),";
//                    $insert2 .= "(0, {$v},'任务审核', '{$content}', {$task_add}, 1, 1, now()),";
                    } else {
                        $insert .= "({$task_add}, {$v}, 2),";
//                    $insert2 .= "(0, {$v},'任务审核', '{$content}', {$task_add}, 1, 1, now()),";
                    }
                    //发送站内消息给审核人
                    if($v!=8&&$v!=14){
                        //不通知陈总和mj
                        $dingding = new \App\Models\BaseModel();
                        $dingding->taskSend($v,$content1);
                    }
                    $examine_new = DB::table('tidings')->insertGetId(
                        ["user_fs" => 0, "user_js" => $v, "title" => '任务审核', "content" => $content1, "object_id" => $task_add, "object_type" => 1, "type" => 1, "create_time" => now()]
                    );
                    if (!$examine_new) {
                        db::rollback();// 回调
                        return '新增任务审核消息失败--tidings表';
                    }
                    $tiding_id[$k]['id'] = $examine_new;
                    $tiding_id[$k]['user_js'] = $v;
                }
                $insert = rtrim($insert, ",");
//            $insert2 = rtrim($insert2, ",");
                $sql = "insert into tasks_examine(`task_id`, `user_id`, `is_examine`) values {$insert}";
                $tasks_examine_add = db::insert($sql);
                if (!$tasks_examine_add) {
                    db::rollback();// 回调
                    return '新增任务审核失败--tasks_examine表';
                }
            }

            //// 发消息给抄送人
            if (!empty($data['user_cs'])) {
                $content2 = "有新的任务抄送给您，任务：{$data['name']} ，情尽快查看！";
//            $insert = "";
                foreach ($data['user_cs'] as $k => $v) {
                    $cs_new = DB::table('tidings')->insertGetId(
                        ["user_fs" => 0, "user_js" => $v, "title" => '任务抄送', "content" => $content2, "object_id" => $task_add, "object_type" => 1, "type" => 1, "create_time" => now()]
                    );
                    if (!$cs_new) {
                        db::rollback();// 回调
                        return '新增任务抄送失败--tidings表';
                    }
                    $tiding_cs_id[$k]['id'] = $cs_new;
                    $tiding_cs_id[$k]['user_js'] = $v;
                }
            }

            //// 无需审核--触发任务
            if (empty($data['examine'])) {
                // 修改任务状态
                $sql = "update tasks
						set state=3, time_examine='{$time_now}'
						where `Id` = $task_add";
                $task_update = db::update($sql);
                if (!$task_update) {
                    db::rollback();// 回调
                    return '修改任务状态失败--tasks表';
                }

//            $content3 = "您有新的任务: ".$data['desc']."，请尽快处理！";
//
//            $task_tiding = DB::table('tidings')->insertGetId(
//                ["user_fs"=>0,"user_js"=>$data['user_fz'],"title"=>'新任务',"content"=>$content3,"object_id"=>$task_add,"object_type"=>1,"type"=>1,"create_time"=>now()]
//            );
                $arr['task_id'] = $task_add;
                $task_trigger = $this->task_trigger($arr);
                if ($task_trigger != 1) {
                    return $task_trigger;
                }
            }
//            if (isset($data['ext']['request_id'])) {
//                //直接触发任务
//
//                $task_trigger = $this->task_trigger($arr);
//                if ($task_trigger != 1) {
//                    return $task_trigger;
//                }
//            }
            db::commit();// 确认

//        if (isset($tiding_id)) {
//            foreach ($tiding_id as $tidVal) {
//                $this->redis_tiding($tidVal['id'], 0, intVal($tidVal['user_js']), '任务审核', $content1, $task_add, 1, 1);
//            }
//        }
//        if (isset($tiding_cs_id)) {
//            foreach ($tiding_cs_id as $csVal) {
//                $this->redis_tiding($csVal['id'], 0, intVal($csVal['user_js']), '任务抄送', $content2, $task_add, 1, 1);
//            }
//        }
//        if (isset($task_tiding)) {
//            $this->redis_tiding($task_tiding, 0, intVal($data['user_fz']), '新任务', $content3, $task_add, 1, 1);
//        }

            return ['type'=>'success','data'=> $task_add];
        }catch (\Exception $e){
            db::rollback();
            return ['type'=>'fail', '任务新增失败！错误原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }

    }



////////////////////// 任务列表

    /**
     * 任务列表--数据
     * @param list_all 所有数据
     * @param name 任务名称
     * @param user_fz_name 负责人名称
     * @param user_cj_name 创建人名称
     * @param state 状态：1.待审核、2.已拒绝、3.进行中、4.待验收、5.已结束
     * @param type 类型：1.任务、2.任务模板
     * @param type_mb 模板类型：1.财务模板、2.人事模板、3.产品开发
     * @param create_time 创建时间
     */
    public function task_list($data)
    {
        $token = $data['token'];
        $where = "1=1";
        //list_all 所有数据
        if (!$data['list_all']) {
            if ($data['type'] == '1') {
                // 任务
                $where .= " and (t.`user_fz`={$data['user_info']['Id']} or t.`user_cj`={$data['user_info']['Id']})";
            } else if ($data['type'] == '2') {
                // 任务模板
                if ($data['user_info']['Id'] != 527){
                    $where .= " and t.`user_cj`={$data['user_info']['Id']}";
                }
            }
        }
        // 过滤已删除的数据
        $where .= " and t.`is_deleted` = 0";

        //name 任务名称
        if (isset($data['name'])) {
            $where .= " and t.`name` like '%{$data['name']}%'";
        }
        //user_fz_name 负责人名称
        if (isset($data['user_fz_name'])) {
            $where .= " and u_fz.`account` like '%{$data['user_fz_name']}%'";
        }
        //task_keys 任务关键字
        if (isset($data['task_keys'])) {
            $where .= " and t.`ext` like '%{$data['task_keys']}%'";
        }
        //user_cj_name 创建人名称
        if (isset($data['user_cj_name'])) {
            $where .= " and u_cj.`account` like '%{$data['user_cj_name']}%'";
        }
        //state 状态：1.待审核、2.已拒绝、3.进行中、4.待验收、5.已结束
        if (isset($data['state'])) {
            $where .= " and t.`state`={$data['state']}";
        }
        //type 类型：1.任务、2.任务模板
        if (isset($data['type'])) {
            $where .= " and t.`type`={$data['type']}";
        }
        //type_mb 模板类型：1.财务模板、2.人事模板、3.产品开发
        if (!empty($data['type_mb'])) {
            $where .= " and t.`type_mb`={$data['type_mb']}";
        }
        //class_id 任务分类
        if (isset($data['class_id'])) {
            $classArr = implode(',',$data['class_id']);
            $where .= " and t.`class_id` in ($classArr)";
        }
        // 任务id搜索
        if (isset($data['task_id']) && !empty($data['task_id'])){
            $where .= " and t.`Id`={$data['task_id']}";
        }

        //create_time 创建时间
        if (!empty($data['create_time'])) {
            $state_time = $data['create_time'][0] . ' 00:00:00';
            $end_time = $data['create_time'][1] . ' 23:59:59';
            $where .= " and t.create_time>='{$state_time}' and t.create_time<='{$end_time}'";
        }

        if (!isset($data['user_id']) || empty($data['user_id'])){
            if (isset($data['token']) && !empty($data['token'])){
                $users = db::table('users')->where('token',$data['token'])->first();
                $data['user_id'] = $users->Id ?? 0;
            }else{
                $data['user_id'] = 0;
            }
        }
        $controller = new Controller();
        $power = $controller->powers(['user_id' => $data['user_id'], 'identity' => ['show_contract_task', 'show_finance_bill_task']]);

        if (!$power['show_contract_task']){
            $classIds = implode(',', [ 23, 78]);
            $where .= " and class_id not in ({$classIds})";
        }
        if (!$power['show_contract_task']){
            $classIds = implode(',', [26, 69, 70, 65]);
            $where .= " and class_id not in ({$classIds})";
        }

        if (isset($data['is_payment'])){
            $billMdl = db::table('financial_bill')
                ->where('is_payment', $data['is_payment'])
                ->get();
            $billNo = [];
            if ($billMdl->isNotEmpty()){
                $billNo = array_unique(array_column($billMdl->toArrayList(), 'bill_no'));
            }
            if (empty($billNo)){
                return ['total' => 0, 'list' => []];
            }else{
                $i = 0;
                $len = count($billNo);
                foreach ($billNo as $k => $v){
                    if ($i == 0){
                        $where .= " and (t.ext like '%".$v."%'";
                    }else{
                        $where .= " or t.ext like '%".$v."%'";
                    }
                    $i += 1;
                    if ($i== $len){
                        $where .= ')';
                    }
                }
            }
        }

        if (isset($data['supplier_name'])){
            $supplierMdl = db::table('suppliers')
                ->where('name', 'like', '%'.$data['supplier_name'].'%')
                ->get(['Id']);
            if ($supplierMdl->isEmpty()){
                return ['total' => 0, 'list' => []];
            }
            $supplierIds = array_column($supplierMdl->toArrayList(), 'Id');
            $billMdl = db::table('financial_bill')
                ->whereIn('supplier_id', $supplierIds)
                ->get(['bill_no']);
            $whereNo = [];
            if ($billMdl->isNotEmpty()){
                $whereNo = array_column($billMdl->toArrayList(), 'bill_no');
            }
            $contractMdl = db::table('cloudhouse_contract_total')
                ->whereIn('supplier_id', $supplierIds)
                ->get(['contract_no']);
            if ($contractMdl->isNotEmpty()){
                $whereNo = array_merge($whereNo, array_column($contractMdl->toArrayList(), 'contract_no'));
            }
            if (empty($whereNo)){
                return ['total' => 0, 'list' => []];
            }else{
                $i = 0;
                $len = count($whereNo);
                foreach ($whereNo as $k => $v){
                    if ($i == 0){
                        $where .= " and (t.ext like '%".$v."%'";
                    }else{
                        $where .= " or t.ext like '%".$v."%'";
                    }
                    $i += 1;
                    if ($i== $len){
                        $where .= ')';
                    }
                }
            }
        }

        // 创建时间动态排序
        $order_by = ' DESC ';
        if (isset($data['order_by']) && !empty($data['order_by'])){
            $order_by = ' ASC ';
        }

        //分页
        $limit = "";
        if ((!empty($data['page'])) and (!empty($data['page_count']))) {
            $limit = " limit " . ($data['page'] - 1) * $data['page_count'] . ",{$data['page_count']}";
        }

        $sql = "select SQL_CALC_FOUND_ROWS t.*,u_fz.account as account_fz, u_cj.account as account_cj
				       from tasks t
				       inner join users u_cj on u_cj.Id = t.user_cj
                       left join users u_fz on u_fz.Id = t.user_fz
				       where {$where}
				       order by t.state asc,t.create_time {$order_by} {$limit}";


        // echo $sql;
        $list = json_decode(json_encode(db::select($sql)), true);

       

        //// 总条数
        if (isset($data['page']) and isset($data['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }

        if (empty($list)) {
            $return['list'] = [];
            $return['code'] = 200;
            $return['msg'] = '获取成功！';
            return $return;
        }
        $task_id = array_column($list, 'Id');

        $tasks_examine = DB::table('tasks_examine as a')
            ->leftJoin('users as b','a.user_id','=','b.Id')
            ->whereIn('task_id', $task_id)
            ->select('a.state','b.account as user_examine','a.task_id')
            ->get()
            ->toArray();

        $notExamine = [];
        $ExamineOk = [];
        $ExamineNo = [];
        foreach ($tasks_examine as $te){
            if($te->state==1||$te->state==2){
                $notExamine[$te->task_id][] = $te->user_examine;
            }elseif($te->state==3){
                $ExamineOk[$te->task_id][] = $te->user_examine;
            }elseif($te->state==4){
                $ExamineNo[$te->task_id][] = $te->user_examine;
            }
        }

        $tasks_news = DB::table('tasks_news as a')
            ->select('a.task_id', 'b.account as user_fs', 'c.account as user_js', 'a.content', 'a.create_time')
            ->leftjoin('users as b', 'b.Id', '=', 'a.user_fs')
            ->leftjoin('users as c', 'c.Id', '=', 'a.user_js')
            ->whereIn('task_id', $task_id)
            ->get();
        // $item['tasks_news'] = json_decode(json_encode($tasks_news), true);
        $tasks_news = json_decode(json_encode($tasks_news), true);


        $shop = Db::table('shop')->select('Id', 'shop_name', 'country_id')->get()->toArray();

        $plan_status = Db::table('amazon_plan_status')->get()->toArray();
        $base = new BaseModel();
        $billMdl = db::table('financial_bill')
            ->get()
            ->keyBy('id');
        $contractMdl = db::table('cloudhouse_contract_total')
            ->get()
            ->keyBy('contract_no');

        $contractSpuMdl = db::table('cloudhouse_contract')
            ->select('contract_no', 'one_price', db::raw('group_concat(spu SEPARATOR ",") as spu'), db::raw('group_concat(spu_id SEPARATOR ",") as spu_id'))
            ->groupBy('contract_no')
            ->get()
            ->keyBy('contract_no');
        foreach ($list as &$item) {
            $item['tasks_news'] = [];
            foreach ($tasks_news as $k => $v) {
                if ($item['Id'] == $v['task_id']) {
                    $item['tasks_news'][] = $v;
                }
            }
            if(isset($notExamine[$item['Id']])){
                $item['not_examine'] = $notExamine[$item['Id']];
            }else{
                $item['not_examine'] = [];
            }

            if(isset($ExamineOk[$item['Id']])){
                $item['examine_ok'] = $ExamineOk[$item['Id']];
            }else{
                $item['examine_ok'] = [];
            }

            if(isset($ExamineNo[$item['Id']])){
                $item['examine_no'] = $ExamineNo[$item['Id']];
            }else{
                $item['examine_no'] = [];
            }
            
            $userCsArr = explode(',', $item['user_cs']);
            $userCs = '';
            foreach ($userCsArr as $userId){
                $userCs .= $base->GetUsers($userId)['account'].' ';
            }
            $item['user_cs_name'] = $userCs;
            $item['sku_count'] = 0;
            $item['sum'] = 0;
            $item['spulist'] = [];
//            $item['father_asin'] = [];
//            $item['father_asin_info'] = [];
            if ($item['ext'] != null && $item['ext'] != '') {
                $ext = json_decode($item['ext'], true);
                $item['ext'] = $ext;

                $TaskClassModule = TaskClassModule::where('class_id', $item['class_id'])->get()->toArray();
                $item['clsss_module'] = $TaskClassModule;

                if (isset($ext['request_id'])) {
                    $detail = DB::table('amazon_buhuo_detail')->where('request_id', '=', $ext['request_id'])->select('id')->get();
                    $item['sku_count'] = count($detail);
                }
                if (isset($ext['start_time'])) {
                    $item['start_time'] = $ext['start_time'];
                }
                if (isset($ext['end_time'])) {
                    $item['end_time'] = $ext['end_time'];
                }
                if (isset($ext['request_link'])) {
                    $item['request_link'] = $ext['request_link'];
                }
                if (isset($ext['request_id'])) {
                    $item['request_id'] = $ext['request_id'];
                    $sql = "SELECT  a.*, c.shop_id, b.fasin,c.request_status
                FROM
                    amazon_buhuo_detail a 
                LEFT JOIN self_sku b ON a.sku_id = b.id
                LEFT JOIN amazon_buhuo_request c ON a.request_id = c.id
                WHERE
                    request_id='" . $item['request_id'] . "'
                ORDER BY
                    a.custom_sku desc";
                    $data = DB::select($sql);
                    $item['shop_name'] = '';
                    $item['transport_type'] = '';
                    $item['request_status'] = '';
                    $sum = 0;
                    $father_asin = [];
                    if(!empty($data)){
                        $custom_sku_idList = array_column($data,'custom_sku_id');
                        foreach ($data as $val) {
                            if (!empty($val->fasin)) {
                                $father_asin[] = $val->fasin;
                            }
                            $sum = $sum + $val->request_num;
                            $shop_arr = $base->GetShop($val->shop_id);
                            $item['shop_name'] = $shop_arr['account'];
                            $item['country_id'] = $shop_arr['country_id'];
                            $iten['shop_id'] = $val->shop_id;

                            $request_status = $val->request_status;

                            $item['request_status'] = $base->GetPlan($request_status)['status_name'];
//                            $plan_arr = array_filter($plan_status, function ($t) use ($request_status) {
//                                return $t->id == $request_status;
//                            });
//                            $item['request_status'] = array_column($plan_arr,'status_name')[0];

                            $item['transport_type'] = $val->transportation_mode_name;
                        }
                    }
                    if(isset($father_asin)){
                        $item['father_asin'] = array_unique($father_asin);
                    }
                    $item['sum'] = $sum;
                }



                if(isset($ext['request_id'])){

                    $order = db::table('amazon_buhuo_detail')->where('request_id',$ext['request_id'])->get()->toarray();
                    if($order){
                        $sku_ids = array_unique(array_column($order,'sku_id'));
                        $spu_ids = array_unique(array_column($order,'spu_id'));
                        $spus = array_unique(array_column($order,'spu'));
                        $spu_with_id = array_unique(array_column($order,'spu','spu_id'));
                        foreach ($spus as $sp){
                            $item['spulist'][]['spu'] = $sp;
                        }
                        $skures = db::table('self_sku')->whereIn('id',$sku_ids)->get()->toarray();
                        $father_asin = array_unique(array_column($skures,'fasin'));
                        if(isset($father_asin)){
                            //查询周转天数
                            $inventory_days = db::table('inventory_day_fasin')->whereIn('fasin',$father_asin)->get();
                            $new_fasin = [];
                            foreach ($inventory_days as $fav) {
                                # code...
                                $new_fasin[$fav->fasin]['fasin'] = $fav->fasin;
                              
                                if($order[0]->shop_id>0){
                                    $new_fasin[$fav->fasin]['fasin_code'] = db::table('amazon_fasin_bind')->where('fasin',$fav->fasin)->where('shop_id',
                                            $order[0]->shop_id)->first()->fasin_code??'';
                                }else{
                                    $new_fasin[$fav->fasin]['fasin_code'] = '';
                                }
                                
                                if($fav->find_day==7){
                                    $new_fasin[$fav->fasin]['w_fba_days']= $fav->fba_days;
                                    $new_fasin[$fav->fasin]['w_here_days']= $fav->here_days;
                                }
                                if($fav->find_day==30){
                                    $new_fasin[$fav->fasin]['m_fba_days']= $fav->fba_days;
                                    $new_fasin[$fav->fasin]['m_here_days']= $fav->here_days;
                                }
                                if($fav->find_day==90){
                                    $new_fasin[$fav->fasin]['tm_fba_days']= $fav->fba_days;
                                    $new_fasin[$fav->fasin]['tm_here_days']= $fav->here_days;
                                }
                               
                            }
    
                            $new_fasin_b = [];
                            foreach ($father_asin as $faav) {
                                # code...
                                if(isset($new_fasin[$faav])){
                                    $new_fasin_b[] = $new_fasin[$faav];
                                }else{
                                    $new_fasin_b[] = ["fasin"=>$faav,'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                                }
                               
                            }
                            $item['father_asin'] = $father_asin;
                            $item['father_asin_info'] = $new_fasin_b;
    
                        }
    
    
                        if(!empty($spu_ids)){
    
                          
                            //查询周转天数
                            $spu_inventory_days = db::table('inventory_day_spu')->whereIn('spu_id',$spu_ids)->get();
                            $new_spus = [];
                            foreach ($spu_inventory_days as $spav) {
                                # code...
                                $new_spus[$spav->spu_id]['spu_id'] = $spav->spu_id;
                                $new_spus[$spav->spu_id]['spu'] = $spu_with_id[$spav->spu_id];
                                if($spav->find_day==7){
                                    $new_spus[$spav->spu_id]['w_fba_days']= $spav->fba_days;
                                    $new_spus[$spav->spu_id]['w_here_days']= $spav->here_days;
                                }
                                if($spav->find_day==30){
                                    $new_spus[$spav->spu_id]['m_fba_days']= $spav->fba_days;
                                    $new_spus[$spav->spu_id]['m_here_days']= $spav->here_days;
                                }
                                if($spav->find_day==90){
                                    $new_spus[$spav->spu_id]['tm_fba_days']= $spav->fba_days;
                                    $new_spus[$spav->spu_id]['tm_here_days']= $spav->here_days;
                                }
                               
                            }
    
                            $new_spus_b = [];
                            foreach ($spu_ids as $spaav) {
                                # code...
                                if(isset($new_spus[$spaav])){
                                    $new_spus_b[] = $new_spus[$spaav];
                                }else{
                                    $new_spus_b[] = ["spu_id"=>$spaav,"spu"=>$spu_with_id[$spaav],'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                                }
                               
                            }
                            $item['spu_info'] = $new_spus_b;
    
                        }


                    }




                }

                if(isset($ext['order_id'])){
                    $order = DB::table('amazon_place_order_task')->where('id', '=', $ext['order_id'])->select('order_num','shop_id','spulist','status','mode','one_ids','platform_id')->first();
                    $order = json_decode(json_encode($order),true);

                    if($order['mode']==1){
                        $one_ids = explode(',',$order['one_ids']);
                        foreach ($one_ids as $i){
                            $task_one = DB::table('amazon_team_task_one')->where('id',$i)->select('shop_id')->first();
                            if (empty($task_one)){
                                continue;
                            }
                            $task_detail = DB::table('amazon_team_task_detail')->where('order_id',$i)->select('custom_sku_id','order_num','suppliers_price','spu_id','spu')->get();
                            $task_detail = json_decode(json_encode($task_detail),true);
                            $total_price = 0;
                            $spu_price = [];
                            foreach ($task_detail as $td){
                                if(!isset($spu_price[$td['spu_id']])){
                                    $spu_price[$td['spu_id']] = $td['suppliers_price'];
                                }
                                $custom_sku_idList[] = $td['custom_sku_id'];
                                $orderNum = json_decode($td['order_num'],true);
                                $orderNumSum = array_sum($orderNum);
                                $total_price += $orderNumSum*$td['suppliers_price'];
                            }
                            $asinlist = DB::table('self_sku')->where('shop_id',$task_one->shop_id)->whereIn('custom_sku_id',$custom_sku_idList)->select('fasin')->distinct()->get();
                            if(!empty($asinlist)){
                                foreach ($asinlist as $as){
                                    if ($as->fasin != '' ||  $as->fasin != null){
                                        $father_asin[] = $as->fasin;
                                    }
                                }
                            }
                        }
                    }
                    if($order['mode']==2){
                        $task_detail =  DB::table('amazon_place_order_detail')->where('order_id',$ext['order_id'])->select('custom_sku_id','order_num','suppliers_price','spu_id','spu')->get();
                        $task_detail = json_decode(json_encode($task_detail),true);
                        $custom_sku_idList = [];
                        $total_price = 0;
                        foreach ($task_detail as $td){
                            if(!isset($spu_price[$td['spu_id']])){
                                $spu_price[$td['spu_id']] = $td['suppliers_price'];
                            }
                            $custom_sku_idList[] = $td['custom_sku_id'];
                            $orderNum = json_decode($td['order_num'],true);
                            $orderNumSum = array_sum($orderNum);
                            $total_price += $orderNumSum*$td['suppliers_price'];
                        }
                        $asinlist = DB::table('self_sku')->where('shop_id',$order['shop_id'])->whereIn('custom_sku_id',$custom_sku_idList)->select('fasin')->distinct()->get();
                        if(!empty($asinlist)){
                            foreach ($asinlist as $as){
                                if ($as->fasin != '' ||  $as->fasin != null){
                                    $father_asin[] = $as->fasin;
                                }
                            }
                        }
                    }
//                    $item['sku_count'] = $order->sku_count;
                    $spu_list = explode(',',$order['spulist']);
                    foreach ($spu_list as $sk=>$sp){
                        $item['spulist'][$sk]['spu'] = $sp;
                        $thisSpuId = $base->GetSpuId($sp);
                        $item['spulist'][$sk]['one_price'] = '未知价格';
                        if(isset($spu_price[$thisSpuId])){
                            $item['spulist'][$sk]['one_price'] = $spu_price[$thisSpuId];
                        }
                    }
                    $item['sum'] = $order['order_num'];
                    $item['task_status'] = $order['status'];
                    $shop = $base->GetShop($order['shop_id']);
                    $item['shop_name'] = $shop['account'];
                    $item['country_id'] = $shop['country_id'];
                    $item['father_asin'] = [];
                    $item['shop_id'] = $order['shop_id'];
                    $item['platform_name'] = '';
                    $item['total_price'] = isset($total_price)? round($total_price,2):0;
                    $item['one_price'] = 0;
                    if($item['sum']>0){
                        $item['one_price'] = round($item['total_price']/$item['sum'],2);
                    }
         
                    if($order['platform_id']>0){
                        $item['platform_name'] = db::table('platform')->where('Id',$order['platform_id'])->select('name')->first()->name??'';
                    }
                    if(isset($father_asin)){

                        $father_asin = array_unique($father_asin);
                        //查询周转天数
                        $inventory_days = db::table('inventory_day_fasin')->whereIn('fasin',$father_asin)->get();
                        $new_fasin = [];
                        foreach ($inventory_days as $fav) {
                            # code...
                            $new_fasin[$fav->fasin]['fasin'] = $fav->fasin;
                            if($item['shop_id']>0){
                                $fasin_codes =  db::table('amazon_fasin_bind')->where('fasin',$fav->fasin)->where('shop_id',$item['shop_id'])->first();
                                if($fasin_codes){
                                    $new_fasin[$fav->fasin]['fasin_code'] =$fasin_codes->fasin_code;
                                }else{
                                    $new_fasin[$fav->fasin]['fasin_code'] = '';
                                }
                               
                            }else{
                                $new_fasin[$fav->fasin]['fasin_code'] = '';
                            }

                            if($fav->find_day==7){
                                $new_fasin[$fav->fasin]['w_fba_days']= $fav->fba_days;
                                $new_fasin[$fav->fasin]['w_here_days']= $fav->here_days;
                            }
                            if($fav->find_day==30){
                                $new_fasin[$fav->fasin]['m_fba_days']= $fav->fba_days;
                                $new_fasin[$fav->fasin]['m_here_days']= $fav->here_days;
                            }
                            if($fav->find_day==90){
                                $new_fasin[$fav->fasin]['tm_fba_days']= $fav->fba_days;
                                $new_fasin[$fav->fasin]['tm_here_days']= $fav->here_days;
                            }
                           
                        }

                        $new_fasin_b = [];
                        foreach ($father_asin as $faav) {
                            # code...
                            if(isset($new_fasin[$faav])){
                                $new_fasin_b[] = $new_fasin[$faav];
                            }else{
                                $new_fasin_b[] = ["fasin"=>$faav,'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                            }
                           
                        }
                        $item['father_asin'] = $father_asin;
                        $item['father_asin_info'] = $new_fasin_b;

                    }


                    if(isset($order['spulist'])){
                        $spu_list_ids = [];
                        $spu_with_id = [];
                        foreach ($spu_list as $spuone) {
                            # code...
                            $spu_id = db::table('self_spu')->where('spu',$spuone)->orwhere('old_spu',$spuone)->first();
                            if($spu_id){
                                $spu_list_ids[] = $spu_id->id;
                                $spu_with_id[$spu_id->id] = $spuone;
                            } 
                        }
                        //查询周转天数
                        $spu_inventory_days = db::table('inventory_day_spu')->whereIn('spu_id',$spu_list_ids)->get();
                        $new_spus = [];
                        foreach ($spu_inventory_days as $spav) {
                            # code...
                            $new_spus[$spav->spu_id]['spu_id'] = $spav->spu_id;
                            $new_spus[$spav->spu_id]['spu'] = $spu_with_id[$spav->spu_id];
                            if($spav->find_day==7){
                                $new_spus[$spav->spu_id]['w_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['w_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==30){
                                $new_spus[$spav->spu_id]['m_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['m_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==90){
                                $new_spus[$spav->spu_id]['tm_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['tm_here_days']= $spav->here_days;
                            }
                           
                        }

                        $new_spus_b = [];
                        foreach ($spu_list_ids as $spaav) {
                            # code...
                            if(isset($new_spus[$spaav])){
                                $new_spus_b[] = $new_spus[$spaav];
                            }else{
                                $new_spus_b[] = ["spu_id"=>$spaav,"spu"=>$spu_with_id[$spaav],'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                            }
                           
                        }
                        $item['spu_info'] = $new_spus_b;

                    }



                }

                if(isset($ext['transfers_id'])){
                    $goods_transfers = DB::table('goods_transfers')->where('order_no',$ext['transfers_id'])->select('platform_id')->first();
                    $item['platform_name'] = '';
                    if(!empty($goods_transfers)){
                        if($goods_transfers->platform_id>0){
                            $item['platform_name'] = db::table('platform')->where('Id',$goods_transfers->platform_id)->select('name')->first()->name??'';
                        }

                    }
                }

                $fasinCode = [];
                $fasin_v_code = [];
                if (isset($item['father_asin'])){
                    foreach ($item['father_asin'] as $fasin){
                        $fasinCodeMdl = $base->GetFasinCodeNew($fasin, $item['shop_id']);
//                        if ($token == '660B08F029946C65247AC7204F1C5A72'){
//                            var_dump($fasin);
//                            var_dump($item['shop_id']);
//                            var_dump($fasinCodeMdl);
//                        }
                        if ($item['shop_id']){
                            if (!empty($fasinCodeMdl)){
                                $fasin_v_code[$fasin] = $fasinCodeMdl['fasin_code'];
                                $fasinCode[] = $fasinCodeMdl['fasin_code'] ?? '';
                            }
                        }
                        //else{
                        //     if (!empty($fasinCodeMdl)){
                        //         $fasin_cdoe = array_column($fasinCodeMdl, 'fasin_code');
                        //         $fasinCode = array_merge($fasin_cdoe,$fasinCode);
                        //         $fasin_v_code[$fasin] =  $fasin_cdoe;
                        //     }
                        // }
                    }
                    $item['fasin_code'] = $fasinCode;
                }


                if(!empty($item['shop_id'])){
                    $shop_id = $item['shop_id'];
                    $shop_arr = $base->GetShop($shop_id);
                    $item['shop_name'] = $shop_arr['account'];
                    $item['country_id'] = $shop_arr['country_id'];
//                    $shop_arr = array_filter($shop, function ($t) use ($shop_id) {
//                        return $t->Id == $shop_id;
//                    });
//                    $item['country_id'] = array_column($shop_arr, 'country_id')[0];
//                    $item['shop_name'] = array_column($shop_arr, 'shop_name')[0];
                }

//                 $fasinCode = [];
//                 if (isset($item['father_asin'])){
//                     foreach ($item['father_asin'] as $fasin){
//                         $fasinCodeMdl = $base->GetFasinCodeNew($fasin, $item['shop_id']);
// //                        if ($token == '660B08F029946C65247AC7204F1C5A72'){
// //                            var_dump($fasin);
// //                            var_dump($item['shop_id']);
// //                            var_dump($fasinCodeMdl);
// //                        }
//                         if ($item['shop_id']){
//                             if (!empty($fasinCodeMdl)){
//                                 $fasinCode[] = $fasinCodeMdl['fasin_code'] ?? '';
//                             }
//                         }else{
//                             if (!empty($fasinCodeMdl)){
//                                 $fasin_cdoe = array_column($fasinCodeMdl, 'fasin_code');
//                                 $fasinCode = array_merge($fasin_cdoe,$fasinCode);
//                             }
//                         }
//                     }
//                     $item['fasin_code'] = $fasinCode;
//                 }
//                if (isset($ext['tasks_ext'])) {
//                    $item['tasks_text'] = $ext['tasks_text'];
//                }
//                if (isset($ext['tasks_img'])) {
//                    $item['tasks_img'] = $ext['tasks_img'];
//                }
//                if (isset($ext['tasks_file'])) {
//                    $item['tasks_file'] = $ext['tasks_file'];
//                }
                $item['is_print_pdf'] = '未打印';
                if (isset($ext['bill_id'])){
                    $bill = $billMdl[$ext['bill_id']] ?? [];
                    if (!empty($bill)){
                        $item['bill_id'] = $bill->id; // 票据id
                        $item['bill_no'] = $bill->bill_no; // 票据号
                        $item['status'] = $bill->status; // 票据状态
                        $item['status_name'] = Constant::BILL_STATUS[$bill->status] ?? ''; // 票据状态名称
                        $item['bill_type'] = $bill->bill_type; // 票据类型
                        $item['bill_type_name'] = Constant::BILL_TYPE[$bill->bill_type] ?? ''; // 票据类型名称
                        $item['contract_no'] = $bill->contract_no; // 合同号
                        $item['ratio'] = $bill->ratio; // 比率
                        $item['ratio_name'] = $bill->ratio.'%'; // 比率名称
                        $item['payable_amount'] = $bill->payable_amount; // 应付金额
                        $item['actual_payment'] = $bill->actual_payment; // 实付金额
                        $item['is_disposable_deduction'] = $bill->is_disposable_deduction ? '一次性抵扣' : '非一次性抵扣'; // 是否一次性抵扣
                        $item['deduction_ratio'] = $bill->deduction_ratio.'%'; // 抵扣比率
                        $item['deduction_amount'] = $bill->deduction_amount; // 抵扣金额
                        $item['user_name'] = $base->GetUsers($bill->user_id)['account'] ?? ''; // 经办人名称
                        $item['is_payment_name'] = $bill->is_payment ? '已支付':'未支付'; // 是否支付
                        $item['payment_date'] = $bill->payment_date; // 支付时间
                        $item['unit_price'] = $bill->unit_price; // 单价
                        $item['pricing_quantity'] = $bill->pricing_quantity; // 数量
                        $item['memo'] = $bill->memo; // 票据备注
                        $item['created_at'] = $bill->created_at; // 创建时间
                        $item['supplier_name'] = $bill->supplier_name;
                        $item['company_name'] = $bill->company_name;
                        $item['ext']['supplier_name'] = $bill->supplier_name;
                        $item['ext']['company_name'] = $bill->company_name;
                        $item['clsss_module'][] = [
                            'id' => 0,
                            'label' => '供应商名称',
                            'name' => 'supplier_name',
                            'type' => 1,
                            'api' => '',
                            'class_id' => 0,
                            'api_id' => 0,
                            'api_label' => '',
                            'api_param' => []
                        ];
                        $item['clsss_module'][] = [
                            'id' => 0,
                            'label' => '公司抬头',
                            'name' => 'company_name',
                            'type' => 1,
                            'api' => '',
                            'class_id' => 0,
                            'api_id' => 0,
                            'api_label' => '',
                            'api_param' => []
                        ];
                    }
                }

                $item['is_print_pdf'] = '未打印';
                if (isset($ext['contract_no'])){
                    $contract = $contractMdl[$ext['contract_no']] ?? [];
                    $contractSpu = $contractSpuMdl[$ext['contract_no']] ?? [];
                    $item['is_print_pdf'] = isset($contract->is_print_pdf)&&$contract->is_print_pdf == 1 ? '已打印' : '未打印';

                    $spuList = array_unique(explode(',', $contractSpu->spu ?? ''));
                    foreach ($spuList as $sp){
                        $item['spulist'][]['spu'] = $sp;
                    }

                    $item['ext']['supplier_name'] = $contract->supplier_short_name ?? '';
                    $item['ext']['company_name'] = $contract->company_name ?? '';
                    // 逆天啊
                    $item['clsss_module'][] = [
                        'id' => 0,
                        'label' => '供应商名称',
                        'name' => 'supplier_name',
                        'type' => 1,
                        'api' => '',
                        'class_id' => 0,
                        'api_id' => 0,
                        'api_label' => '',
                        'api_param' => []
                    ];
                    $item['clsss_module'][] = [
                        'id' => 0,
                        'label' => '公司抬头',
                        'name' => 'company_name',
                        'type' => 1,
                        'api' => '',
                        'class_id' => 0,
                        'api_id' => 0,
                        'api_label' => '',
                        'api_param' => []
                    ];
                    if(isset($spuList) && !empty($spuList)){
                        $spu_list_ids = [];
                        $spu_with_id = [];
                        foreach ($spuList as $spuone) {
                            # code...
                            $spu_id = db::table('self_spu')->where('spu',$spuone)->orwhere('old_spu',$spuone)->first();
                            if($spu_id){
                                $spu_list_ids[] = $spu_id->id;
                                $spu_with_id[$spu_id->id] = $spuone;
                            }
                        }
                        //查询周转天数
                        $spu_inventory_days = db::table('inventory_day_spu')->whereIn('spu_id',$spu_list_ids)->get();
                        $new_spus = [];
                        foreach ($spu_inventory_days as $spav) {
                            # code...
                            $new_spus[$spav->spu_id]['spu_id'] = $spav->spu_id;
                            $new_spus[$spav->spu_id]['spu'] = $spu_with_id[$spav->spu_id];
                            if($spav->find_day==7){
                                $new_spus[$spav->spu_id]['w_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['w_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==30){
                                $new_spus[$spav->spu_id]['m_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['m_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==90){
                                $new_spus[$spav->spu_id]['tm_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['tm_here_days']= $spav->here_days;
                            }

                        }

                        $new_spus_b = [];
                        foreach ($spu_list_ids as $spaav) {
                            # code...
                            if(isset($new_spus[$spaav])){
                                $new_spus_b[] = $new_spus[$spaav];
                            }else{
                                $new_spus_b[] = ["spu_id"=>$spaav,"spu"=>$spu_with_id[$spaav],'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                            }

                        }
                        $item['spu_info'] = $new_spus_b;

                    }
                }
            }
        }




        if (isset($data['is_payment'])){
            $posttype=$data['posttype']??1;
            if($data['is_payment']==1){
                $p['title']='预付账单审核列表-已支付'.time();
            }else{
                $p['title']='预付账单审核列表-待支付'.time();
            }
            if($posttype==2){
                $p['title_list'] = [
                    'spu'=>'spu',
                    'color' => '颜色',
                    'img' => '图片',
                    'day_quantity_ordered'=>'日销',
                    'order_num'=>'销量',
                    'conversion_rate_e'=>'转化率',
                    'return_rate_e'=>'退货率',
                    'return_num'=>'退货数量',
                    'tongan_num'=>'同安仓库存',
                    'quanzhou_num'=>'泉州仓库存',
                    'cloud_num'=>'云仓库存',
                    'factory_num'=>'工厂虚拟仓库存',
                    'total_inventory'=>'总库存',
                    'in_stock_num'=>'fba在仓',
                    'transfer_num'=>'fba预留',
                    'in_bound_num'=>'fba在途',
                    'here_inventory_day'=>'本地仓周转天数',
                    'fba_inventory_day'=>'fba仓周转天数',
                    'fba_inventory_day'=>'fba仓周转天数',
                    'fisrt_order_time'=>'首单时间',
                ];
    
                $p['data'] =   $list;
                
                $p['user_id'] =  db::table('users')->where('token',$token)->first()->Id;  
                $p['type'] = '预付账单审核列表-导出';
    
                $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
                try {
                    $job::runJob($p);
                } catch(\Exception $e){
                    return ['code' => 500, 'msg' => '加入队列失败'];
                }
                return ['code' => 200,'msg' => '加入队列成功', 'list' => $list, 'count' => $total];
            }
        }
        $return['list'] = $list;
        $return['code'] = 200;
        $return['msg'] = '获取成功！';
        return $return;
    }



    /**
     * 待审核列表--数据
     * @param name 任务名称
     * @param user_fz_name 负责人名称
     * @param state 状态：1.待审核、2.已拒绝、3.进行中、4.待验收、5.已结束
     * @param type 类型：1.任务、2.任务模板
     * @param create_time 创建时间
     */
    public function task_audit_list($data)
    {
        $where = "t.type=1 and t.state not in (2,4,5)";
        // 过滤已删除的数据
        $where .= " and t.`is_deleted` = 0";
//        $day = date("l");
//        if($day!='Wednesday'){
//            $where .=" and t.class_id!=19";
//        }
        //name 任务名称
        if (isset($data['name'])) {
            $where .= " and t.`name` like '%{$data['name']}%'";
        }
        //user_fz_name 负责人名称
        if (isset($data['user_fz_name'])) {
            $where .= " and u_fz.`account` like '%{$data['user_fz_name']}%'";
        }
        //user_cj_name 创建人名称
        if (isset($data['user_cj_name'])) {
            $where .= " and u_cj.`account` like '%{$data['user_cj_name']}%'";
        }
        //task_keys 任务关键字
        if (isset($data['task_keys'])) {
            $where .= " and t.`ext` like '%{$data['task_keys']}%'";
        }
        if (isset($data['examine_state'])) {
            $examine_state = implode(",", $data['examine_state']);
            $where .= " and te.`state` in ($examine_state)";
        }
        //class_id 任务分类
        if (isset($data['class_id'])) {
            $classArr = implode(',',$data['class_id']);
            $where .= " and t.`class_id` in ($classArr)";
        }
        if (isset($data['task_id'])) {
            $where .= " and t.`Id`={$data['task_id']}";
        }

        if (isset($data['supplier_name'])){
            $supplierMdl = db::table('suppliers')
                ->where('name', 'like', '%'.$data['supplier_name'].'%')
                ->get(['Id']);
            if ($supplierMdl->isEmpty()){
                return ['total' => 0, 'list' => []];
            }
            $supplierIds = array_column($supplierMdl->toArrayList(), 'Id');
            $billMdl = db::table('financial_bill')
                ->whereIn('supplier_id', $supplierIds)
                ->get(['bill_no']);
            $whereNo = [];
            if ($billMdl->isNotEmpty()){
                $whereNo = array_column($billMdl->toArrayList(), 'bill_no');
            }
            $contractMdl = db::table('cloudhouse_contract_total')
                ->whereIn('supplier_id', $supplierIds)
                ->get(['contract_no']);
            if ($contractMdl->isNotEmpty()){
                $whereNo = array_merge($whereNo, array_column($contractMdl->toArrayList(), 'contract_no'));
            }
            if (empty($whereNo)){
                return ['total' => 0, 'list' => []];
            }else{
                $i = 0;
                $len = count($whereNo);
                foreach ($whereNo as $k => $v){
                    if ($i == 0){
                        $where .= " and (t.ext like '%".$v."%'";
                    }else{
                        $where .= " or t.ext like '%".$v."%'";
                    }
                    $i += 1;
                    if ($i== $len){
                        $where .= ')';
                    }
                }
            }
        }

        //create_time 创建时间
        if (!empty($data['create_time'])) {
            $state_time = $data['create_time'][0] . ' 00:00:00';
            $end_time = $data['create_time'][1] . ' 23:59:59';
            $where .= " and t.create_time>='{$state_time}' and t.create_time<='{$end_time}'";
        }

        //分页
        $limit = "";
        if ((!empty($data['page'])) and (!empty($data['page_count']))) {
            $limit = " limit " . ($data['page'] - 1) * $data['page_count'] . ",{$data['page_count']}";
        }

        $sql = "select SQL_CALC_FOUND_ROWS t.*,u_fz.account as account_fz, u_cj.account as account_cj ,te.state as examine_state
				       from tasks t
				       inner join users u_fz on u_fz.Id = t.user_fz
				       inner join users u_cj on u_cj.Id = t.user_cj
				       inner join tasks_examine te on te.task_id=t.Id and te.is_examine=2 and te.user_id={$data['user_info']['Id']}
				       where {$where}
				       order by t.create_time asc {$limit}";
        $list = json_decode(json_encode(db::select($sql)), true);

        //// 总条数
        if (isset($data['page']) and isset($data['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }

        if (empty($list)) {
            $return['list'] = [];
            return $return;
        }
        $task_id = array_column($list, 'Id');
        $base = new BaseModel();

        $tasks_examine = DB::table('tasks_examine as a')
            ->leftJoin('users as b','a.user_id','=','b.Id')
            ->whereIn('task_id', $task_id)
            ->select('a.state','b.account as user_examine','a.task_id')
            ->get()
            ->toArray();

        $notExamine = [];
        $ExamineOk = [];
        $ExamineNo = [];
        foreach ($tasks_examine as $te){
            if($te->state==1||$te->state==2){
                $notExamine[$te->task_id][] = $te->user_examine;
            }elseif($te->state==3){
                $ExamineOk[$te->task_id][] = $te->user_examine;
            }elseif($te->state==4){
                $ExamineNo[$te->task_id][] = $te->user_examine;
            }
        }

        $tasks_news = DB::table('tasks_news as a')
            ->select('a.task_id', 'b.account as user_fs', 'c.account as user_js', 'a.content', 'a.create_time')
            ->leftjoin('users as b', 'b.Id', '=', 'a.user_fs')
            ->leftjoin('users as c', 'c.Id', '=', 'a.user_js')
            ->whereIn('task_id', $task_id)
            ->get();
        $contractMdl = db::table('cloudhouse_contract_total')
            ->get()
            ->keyBy('contract_no');

        $contractSpuMdl = db::table('cloudhouse_contract')
            ->select('contract_no', 'one_price', db::raw('group_concat(spu SEPARATOR ",") as spu'), db::raw('group_concat(spu_id SEPARATOR ",") as spu_id'))
            ->groupBy('contract_no')
            ->get()
            ->keyBy('contract_no');

        $tasks_news = json_decode(json_encode($tasks_news), true);
        $shop = Db::table('shop')->select('Id', 'shop_name', 'country_id')->get()->toArray();
        $plan_status = Db::table('amazon_plan_status')->get()->toArray();
        foreach ($list as $key=>&$item) {
            $item['tasks_news'] = [];
            foreach ($tasks_news as $k => $v) {
                if ($item['Id'] == $v['task_id']) {
                    $item['tasks_news'][] = $v;
                }
            }

            if(isset($notExamine[$item['Id']])){
                $item['not_examine'] = $notExamine[$item['Id']];
            }else{
                $item['not_examine'] = [];
            }

            if(isset($ExamineOk[$item['Id']])){
                $item['examine_ok'] = $ExamineOk[$item['Id']];
            }else{
                $item['examine_ok'] = [];
            }

            if(isset($ExamineNo[$item['Id']])){
                $item['examine_no'] = $ExamineNo[$item['Id']];
            }else{
                $item['examine_no'] = [];
            }


            $item['sku_count'] = 0;
            $item['sum'] = 0;
            $item['spulist'] = [];
            $item['father_asin'] = [];
            $item['father_asin_info'] = [];
            if (!empty($item['ext'])) {
                $ext = json_decode($item['ext'], true);
                $item['ext'] = $ext;
                $TaskClassModule = TaskClassModule::where('class_id', $item['class_id'])->get()->toArray();
                $item['clsss_module'] = $TaskClassModule;
                if (isset($ext['request_id'])) {
                    $detail = DB::table('amazon_buhuo_detail')->where('request_id', '=', $ext['request_id'])->select('id')->get();
                   
                    $item['sku_count'] = count($detail);
                }
                if (isset($ext['start_time'])) {
                    $item['start_time'] = $ext['start_time'];
                }
                if (isset($ext['end_time'])) {
                    $item['end_time'] = $ext['end_time'];
                }
                if (isset($ext['request_link'])) {
                    $item['request_link'] = $ext['request_link'];
                }
                if (isset($ext['request_id'])) {
                    $item['request_id'] = $ext['request_id'];

                    $sql = "SELECT  a.request_num, a.transportation_mode_name, a.transportation_type, c.shop_id, c.transportation_date ,b.fasin,c.request_status
                FROM
                    amazon_buhuo_detail a 
                LEFT JOIN self_sku b ON a.sku_id = b.id
                LEFT JOIN amazon_buhuo_request c ON a.request_id = c.id
                WHERE
                    request_id='" . $item['request_id'] . "'
                ORDER BY
                    a.custom_sku desc";
                    $data = DB::select($sql);
                    $item['shop_name'] = '';
                    $item['transport_type'] = '';
                    $item['request_status'] = '';
                    $item['transport_date'] = '';
                    $sum = 0;
                    $father_asin = [];
                    foreach ($data as $val) {
                        if ($val->fasin != '' || $val->fasin != null) {
                            $father_asin[] = $val->fasin;
                        }
                        $sum = $sum + $val->request_num;
                        $shop_arr = $base->GetShop($val->shop_id);
                        $item['shop_name'] = $shop_arr['account'];
                        $item['country_id'] = $shop_arr['country_id'];
                        $item['shop_id'] = $val->shop_id;

                        $request_status = $val->request_status;
                        $item['request_status'] = $base->GetPlan($request_status)['status_name'];

                        $item['transport_type'] = $val->transportation_mode_name;
                        $item['transport_date'] = date('Y-m-d', strtotime($val->transportation_date));
                    }
                    $item['father_asin'] = array_unique($father_asin);
                    $item['sum'] = $sum;


                    $order = db::table('amazon_buhuo_detail')->where('request_id', $ext['request_id'])->get()->toarray();
                    if ($order) {
                        $sku_ids = array_unique(array_column($order, 'sku_id'));
                        $spu_ids = array_unique(array_column($order, 'spu_id'));
                        $spus = array_unique(array_column($order, 'spu'));
                        $spu_with_id = array_unique(array_column($order, 'spu', 'spu_id'));
                        if (!empty($spus)) {
                            foreach ($spus as $sp) {
                                $item['spulist'][]['spu'] = $sp;
                            }
                        } else {
                            $item['spulist'] = [];
                        }

                        $skures = db::table('self_sku')->whereIn('id', $sku_ids)->get()->toarray();
                        $father_asin = array_unique(array_column($skures, 'fasin'));
                        if (isset($father_asin)) {
                            //查询周转天数
                            $inventory_days = db::table('inventory_day_fasin')->whereIn('fasin', $father_asin)->get();
                            $new_fasin = [];
                            foreach ($inventory_days as $fav) {
                                # code...
                                $new_fasin[$fav->fasin]['fasin'] = $fav->fasin;
                                if ($order[0]->shop_id > 0) {
                                    $new_fasin[$fav->fasin]['fasin_code'] = db::table('amazon_fasin_bind')->where('fasin', $fav->fasin)->where('shop_id', $order[0]->shop_id)->first()->fasin_code ?? '';
                                } else {
                                    $new_fasin[$fav->fasin]['fasin_code'] = '';
                                }

                                if ($fav->find_day == 7) {
                                    $new_fasin[$fav->fasin]['w_fba_days'] = $fav->fba_days;
                                    $new_fasin[$fav->fasin]['w_here_days'] = $fav->here_days;
                                }
                                if ($fav->find_day == 30) {
                                    $new_fasin[$fav->fasin]['m_fba_days'] = $fav->fba_days;
                                    $new_fasin[$fav->fasin]['m_here_days'] = $fav->here_days;
                                }
                                if ($fav->find_day == 90) {
                                    $new_fasin[$fav->fasin]['tm_fba_days'] = $fav->fba_days;
                                    $new_fasin[$fav->fasin]['tm_here_days'] = $fav->here_days;
                                }

                            }

                            $new_fasin_b = [];
                            foreach ($father_asin as $faav) {
                                # code...
                                if (isset($new_fasin[$faav])) {
                                    $new_fasin_b[] = $new_fasin[$faav];
                                } else {
                                    $new_fasin_b[] = ["fasin" => $faav, 'w_fba_days' => 0, 'w_here_days' => 0, 'm_fba_days' => 0, 'm_here_days' => 0, 'tm_fba_days' => 0, 'tm_here_days' => 0];
                                }

                            }
                            $item['father_asin'] = $father_asin;
                            $item['father_asin_info'] = $new_fasin_b;

                        }


                        if (!empty($spu_ids)) {


                            //查询周转天数
                            $spu_inventory_days = db::table('inventory_day_spu')->whereIn('spu_id', $spu_ids)->get();
                            $new_spus = [];
                            foreach ($spu_inventory_days as $spav) {
                                # code...
                                $new_spus[$spav->spu_id]['spu_id'] = $spav->spu_id;
                                $new_spus[$spav->spu_id]['spu'] = $spu_with_id[$spav->spu_id];
                                if ($spav->find_day == 7) {
                                    $new_spus[$spav->spu_id]['w_fba_days'] = $spav->fba_days;
                                    $new_spus[$spav->spu_id]['w_here_days'] = $spav->here_days;
                                }
                                if ($spav->find_day == 30) {
                                    $new_spus[$spav->spu_id]['m_fba_days'] = $spav->fba_days;
                                    $new_spus[$spav->spu_id]['m_here_days'] = $spav->here_days;
                                }
                                if ($spav->find_day == 90) {
                                    $new_spus[$spav->spu_id]['tm_fba_days'] = $spav->fba_days;
                                    $new_spus[$spav->spu_id]['tm_here_days'] = $spav->here_days;
                                }

                            }

                            $new_spus_b = [];
                            foreach ($spu_ids as $spaav) {
                                # code...
                                if (isset($new_spus[$spaav])) {
                                    $new_spus_b[] = $new_spus[$spaav];
                                } else {
                                    $new_spus_b[] = ["spu_id" => $spaav, "spu" => $spu_with_id[$spaav], 'w_fba_days' => 0, 'w_here_days' => 0, 'm_fba_days' => 0, 'm_here_days' => 0, 'tm_fba_days' => 0, 'tm_here_days' => 0];
                                }

                            }
                            $item['spu_info'] = $new_spus_b;

                        }


                    }


                }

                if(isset($ext['order_id'])){
                    $father_asin = [];
                    $order = DB::table('amazon_place_order_task')->where('id', '=', $ext['order_id'])->select('order_num','shop_id','spulist','status','mode','one_ids','platform_id')->first();
                    $order = json_decode(json_encode($order),true);

                    if($order['mode']==1){
                        $one_ids = explode(',',$order['one_ids']);
                        foreach ($one_ids as $i){
                            $task_one = DB::table('amazon_team_task_one')->where('id',$i)->select('shop_id')->first();
                            if (empty($task_one)){
                                continue;
                            }
                            $task_detail = DB::table('amazon_team_task_detail')->where('order_id',$i)->select('custom_sku_id','order_num','suppliers_price','spu_id','spu')->get();
                            $task_detail = json_decode(json_encode($task_detail),true);
                            $total_price = 0;
                            $spu_price = [];
                            foreach ($task_detail as $td){
                                if(!isset($spu_price[$td['spu_id']])){
                                    $spu_price[$td['spu_id']] = $td['suppliers_price'];
                                }
                                $custom_sku_idList[] = $td['custom_sku_id'];
                                $orderNum = json_decode($td['order_num'],true);
                                $orderNumSum = array_sum($orderNum);
                                $total_price += $orderNumSum*$td['suppliers_price'];
                            }
                            $asinlist = DB::table('self_sku')->where('shop_id',$task_one->shop_id)->whereIn('custom_sku_id',$custom_sku_idList)->select('fasin')->distinct()->get();
                            if(!empty($asinlist)){
                                foreach ($asinlist as $as){
                                    if ($as->fasin != '' ||  $as->fasin != null){
                                        $father_asin[] = $as->fasin;
                                    }
                                }
                            }
                        }
                    }
                    if($order['mode']==2){
                        $task_detail =  DB::table('amazon_place_order_detail')->where('order_id',$ext['order_id'])->select('custom_sku_id','order_num','suppliers_price','spu_id','spu')->get();
                        $task_detail = json_decode(json_encode($task_detail),true);
                        $custom_sku_idList = [];
                        $total_price = 0;
                        foreach ($task_detail as $td){
                            if(!isset($spu_price[$td['spu_id']])){
                                $spu_price[$td['spu_id']] = $td['suppliers_price'];
                            }
                            $custom_sku_idList[] = $td['custom_sku_id'];
                            $orderNum = json_decode($td['order_num'],true);
                            $orderNumSum = array_sum($orderNum);
                            $total_price += $orderNumSum*$td['suppliers_price'];
                        }
                        $asinlist = DB::table('self_sku')->where('shop_id',$order['shop_id'])->whereIn('custom_sku_id',$custom_sku_idList)->select('fasin')->distinct()->get();
                        if(!empty($asinlist)){
                            foreach ($asinlist as $as){
                                if ($as->fasin != '' ||  $as->fasin != null){
                                    $father_asin[] = $as->fasin;
                                }
                            }
                        }
                    }

                    $spu_list = explode(',',$order['spulist']);
                    foreach ($spu_list as $sk=>$sp){
                        $item['spulist'][$sk]['spu'] = $sp;
                        $thisSpuId = $base->GetSpuId($sp);
                        $item['spulist'][$sk]['one_price'] = '未知价格';
                        if(isset($spu_price[$thisSpuId])){
                            $item['spulist'][$sk]['one_price'] = $spu_price[$thisSpuId];
                        }
                    }
                    $item['sum'] = $order['order_num'];
                    $item['task_status'] = $order['status'];
                    $shop = $base->GetShop($order['shop_id']);
                    $item['shop_name'] = $shop['account'];
                    $item['country_id'] = $shop['country_id'];
                    $item['father_asin'] = [];
                    $item['shop_id'] = $order['shop_id'];
                    $item['platform_name'] = '';
                    $item['total_price'] = isset($total_price)? round($total_price,2):0;
                    if ($item['sum'] > 0){
                        $item['one_price'] = round($item['total_price']/$item['sum'],2);
                    }else{
                        $item['one_price'] = 0;
                    }

                    if($order['platform_id']>0){
                        $item['platform_name'] = db::table('platform')->where('Id',$order['platform_id'])->select('name')->first()->name??'';
                    }
                    if(!empty($father_asin)){

                        $father_asin = array_unique($father_asin);
                        //查询周转天数
                        $inventory_days = db::table('inventory_day_fasin')->whereIn('fasin',$father_asin)->get();
                        $new_fasin = [];
                        foreach ($inventory_days as $fav) {
                            # code...
                            $new_fasin[$fav->fasin]['fasin'] = $fav->fasin;
                            if($item['shop_id']>0){
                                $fasin_codes =  db::table('amazon_fasin_bind')->where('fasin',$fav->fasin)->where('shop_id',$item['shop_id'])->first();
                                if($fasin_codes){
                                    $new_fasin[$fav->fasin]['fasin_code'] =$fasin_codes->fasin_code;
                                }else{
                                    $new_fasin[$fav->fasin]['fasin_code'] = '';
                                }
                               
                            }else{
                                $new_fasin[$fav->fasin]['fasin_code'] = '';
                            }
                            if($fav->find_day==7){
                                $new_fasin[$fav->fasin]['w_fba_days']= $fav->fba_days;
                                $new_fasin[$fav->fasin]['w_here_days']= $fav->here_days;
                            }
                            if($fav->find_day==30){
                                $new_fasin[$fav->fasin]['m_fba_days']= $fav->fba_days;
                                $new_fasin[$fav->fasin]['m_here_days']= $fav->here_days;
                            }
                            if($fav->find_day==90){
                                $new_fasin[$fav->fasin]['tm_fba_days']= $fav->fba_days;
                                $new_fasin[$fav->fasin]['tm_here_days']= $fav->here_days;
                            }
                           
                        }

                        $new_fasin_b = [];
                        foreach ($father_asin as $faav) {
                            # code...
                            if(isset($new_fasin[$faav])){
                                $new_fasin_b[] = $new_fasin[$faav];
                            }else{
                                $new_fasin_b[] = ["fasin"=>$faav,'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                            }
                           
                        }
                        $item['father_asin'] = $father_asin;
                        $item['father_asin_info'] = $new_fasin_b;

                    }

                    


                    if(isset($order['spulist'])){

                        $spu_list_ids = [];
                        $spu_with_id = [];
                        foreach ($spu_list as $spuone) {
                            # code...
                            $spu_id = db::table('self_spu')->where('spu',$spuone)->orwhere('old_spu',$spuone)->first();
                            if($spu_id){
                                $spu_list_ids[] = $spu_id->id;
                                $spu_with_id[$spu_id->id] = $spuone;
                            } 
                        }
                        //查询周转天数
                        $spu_inventory_days = db::table('inventory_day_spu')->whereIn('spu_id',$spu_list_ids)->get();
                        $new_spus = [];
                        foreach ($spu_inventory_days as $spav) {
                            # code...
                            $new_spus[$spav->spu_id]['spu_id'] = $spav->spu_id;
                            $new_spus[$spav->spu_id]['spu'] = $spu_with_id[$spav->spu_id];
                            if($spav->find_day==7){
                                $new_spus[$spav->spu_id]['w_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['w_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==30){
                                $new_spus[$spav->spu_id]['m_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['m_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==90){
                                $new_spus[$spav->spu_id]['tm_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['tm_here_days']= $spav->here_days;
                            }
                           
                        }

                        $new_spus_b = [];
                        foreach ($spu_list_ids as $spaav) {
                            # code...
                            if(isset($new_spus[$spaav])){
                                $new_spus_b[] = $new_spus[$spaav];
                            }else{
                                $new_spus_b[] = ["spu_id"=>$spaav,"spu"=>$spu_with_id[$spaav],'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                            }
                           
                        }
                        $item['spu_info'] = $new_spus_b;

                    }

    
     


                }

                if(isset($ext['transfers_id'])){
                    $goods_transfers = DB::table('goods_transfers')->where('order_no',$ext['transfers_id'])->select('platform_id')->first();
                    $item['platform_name'] = '';
                    if(!empty($goods_transfers)){
                        if($goods_transfers->platform_id>0){
                            $item['platform_name'] = db::table('platform')->where('Id',$goods_transfers->platform_id)->select('name')->first()->name??'';
                        }

                    }
                }


                $fasinCode = [];
                $fasin_v_code = [];
                if (isset($item['father_asin'])){
                    foreach ($item['father_asin'] as $fasin){
                        $fasinCodeMdl = $base->GetFasinCodeNew($fasin, $item['shop_id']);
//                        if ($token == '660B08F029946C65247AC7204F1C5A72'){
//                            var_dump($fasin);
//                            var_dump($item['shop_id']);
//                            var_dump($fasinCodeMdl);
//                        }
                        if ($item['shop_id']){
                            if (!empty($fasinCodeMdl)){
                                $fasin_v_code[$fasin] = $fasinCodeMdl['fasin_code'];
                                $fasinCode[] = $fasinCodeMdl['fasin_code'] ?? '';
                            }
                        }
                    }
                    $item['fasin_code'] = $fasinCode;
                }

                $item['is_print_pdf'] = '未打印';
                if (isset($ext['contract_no'])){
                    $contract = $contractMdl[$ext['contract_no']] ?? [];
                    $contractSpu = $contractSpuMdl[$ext['contract_no']] ?? [];
                    $item['is_print_pdf'] = isset($contract->is_print_pdf)&&$contract->is_print_pdf == 1 ? '已打印' : '未打印';
                    $spuList = array_unique(explode(',', $contractSpu->spu ?? ''));
                    foreach ($spuList as $sp){
                        $item['spulist'][]['spu'] = $sp;
                    }
                    $item['ext']['supplier_name'] = $contract->supplier_short_name ?? '';
                    $item['ext']['company_name'] = $contract->company_name ?? '';
                    // 逆天啊
                    $item['clsss_module'][] = [
                        'id' => 0,
                        'label' => '供应商名称',
                        'name' => 'supplier_name',
                        'type' => 1,
                        'api' => '',
                        'class_id' => 0,
                        'api_id' => 0,
                        'api_label' => '',
                        'api_param' => []
                    ];
                    $item['clsss_module'][] = [
                        'id' => 0,
                        'label' => '公司抬头',
                        'name' => 'company_name',
                        'type' => 1,
                        'api' => '',
                        'class_id' => 0,
                        'api_id' => 0,
                        'api_label' => '',
                        'api_param' => []
                    ];
                    if(isset($spuList) && !empty($spuList)){
                        $spu_list_ids = [];
                        $spu_with_id = [];
                        foreach ($spuList as $spuone) {
                            # code...
                            $spu_id = db::table('self_spu')->where('spu',$spuone)->orwhere('old_spu',$spuone)->first();
                            if($spu_id){
                                $spu_list_ids[] = $spu_id->id;
                                $spu_with_id[$spu_id->id] = $spuone;
                            }
                        }
                        //查询周转天数
                        $spu_inventory_days = db::table('inventory_day_spu')->whereIn('spu_id',$spu_list_ids)->get();
                        $new_spus = [];
                        foreach ($spu_inventory_days as $spav) {
                            # code...
                            $new_spus[$spav->spu_id]['spu_id'] = $spav->spu_id;
                            $new_spus[$spav->spu_id]['spu'] = $spu_with_id[$spav->spu_id];
                            if($spav->find_day==7){
                                $new_spus[$spav->spu_id]['w_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['w_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==30){
                                $new_spus[$spav->spu_id]['m_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['m_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==90){
                                $new_spus[$spav->spu_id]['tm_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['tm_here_days']= $spav->here_days;
                            }

                        }

                        $new_spus_b = [];
                        foreach ($spu_list_ids as $spaav) {
                            # code...
                            if(isset($new_spus[$spaav])){
                                $new_spus_b[] = $new_spus[$spaav];
                            }else{
                                $new_spus_b[] = ["spu_id"=>$spaav,"spu"=>$spu_with_id[$spaav],'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                            }

                        }
                        $item['spu_info'] = $new_spus_b;

                    }
                }
            }
        }

        $return['list'] = array_values($list);
        return $return;
    }

    /**
     * 已审核列表--数据
     * @param name 任务名称
     * @param user_fz_name 负责人名称
     * @param state 状态：1.待审核、2.已拒绝、3.进行中、4.待验收、5.已结束
     * @param type 类型：1.任务、2.任务模板
     * @param create_time 创建时间
     */
    public function task_reviewed_list($data)
    {
        $where = "t.type = 1 and te.state in(3,4)";
        // 过滤已删除的数据
        $where .= " and t.`is_deleted` = 0";
        //name 任务名称
        if (isset($data['name'])) {
            $where .= " and t.`name` like '%{$data['name']}%'";
        }
        //user_fz_name 负责人名称
        if (isset($data['user_fz_name'])) {
            $where .= " and u_fz.`account` like '%{$data['user_fz_name']}%'";
        }
        //user_cj_name 创建人名称
        if (isset($data['user_cj_name'])) {
            $where .= " and u_cj.`account` like '%{$data['user_cj_name']}%'";
        }
        //class_id 任务分类
        if (isset($data['class_id'])) {
            $classArr = implode(',',$data['class_id']);
            $where .= " and t.`class_id` in ($classArr)";
        }
        //task_keys 任务关键字
        if (isset($data['task_keys'])) {
            $where .= " and t.`ext` like '%{$data['task_keys']}%'";
        }
        //state 状态：1.待审核、2.已拒绝、3.进行中、4.待验收、5.已结束
        if (isset($data['state'])) {
            $where .= " and t.`state`={$data['state']}";
        }

        if (isset($data['supplier_name'])){
            $supplierMdl = db::table('suppliers')
                ->where('name', 'like', '%'.$data['supplier_name'].'%')
                ->get(['Id']);
            if ($supplierMdl->isEmpty()){
                return ['total' => 0, 'list' => []];
            }
            $supplierIds = array_column($supplierMdl->toArrayList(), 'Id');
            $billMdl = db::table('financial_bill')
                ->whereIn('supplier_id', $supplierIds)
                ->get(['bill_no']);
            $whereNo = [];
            if ($billMdl->isNotEmpty()){
                $whereNo = array_column($billMdl->toArrayList(), 'bill_no');
            }
            $contractMdl = db::table('cloudhouse_contract_total')
                ->whereIn('supplier_id', $supplierIds)
                ->get(['contract_no']);
            if ($contractMdl->isNotEmpty()){
                $whereNo = array_merge($whereNo, array_column($contractMdl->toArrayList(), 'contract_no'));
            }
            if (empty($whereNo)){
                return ['total' => 0, 'list' => []];
            }else{
                $i = 0;
                $len = count($whereNo);
                foreach ($whereNo as $k => $v){
                    if ($i == 0){
                        $where .= " and (t.ext like '%".$v."%'";
                    }else{
                        $where .= " or t.ext like '%".$v."%'";
                    }
                    $i += 1;
                    if ($i== $len){
                        $where .= ')';
                    }
                }
            }
        }

        //create_time 创建时间
        if (!empty($data['create_time'])) {
            $state_time = $data['create_time'][0] . ' 00:00:00';
            $end_time = $data['create_time'][1] . ' 23:59:59';
            $where .= " and t.create_time>='{$state_time}' and t.create_time<='{$end_time}'";
        }
        if (isset($data['task_id'])) {
            $where .= " and t.`Id`={$data['task_id']}";
        }
        //分页
        $limit = "";
        if ((!empty($data['page'])) and (!empty($data['page_count']))) {
            $limit = " limit " . ($data['page'] - 1) * $data['page_count'] . ",{$data['page_count']}";
        }

        $sql = "select SQL_CALC_FOUND_ROWS t.*, u_fz.account as account_fz, u_cj.account as account_cj
				       from tasks t
				       inner join users u_fz on u_fz.Id = t.user_fz
				       inner join users u_cj on u_cj.Id = t.user_cj
				       inner join tasks_examine te on te.task_id=t.Id  and te.user_id={$data['user_info']['Id']}
				       where {$where}
				       order by te.time_sh desc {$limit}";
        // echo $sql;
        $list = json_decode(json_encode(db::select($sql)), true);

        //// 总条数
        if (isset($data['page']) and isset($data['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }

        if (empty($list)) {
            $return['list'] = [];
            return $return;
        }
        $task_id = array_column($list, 'Id');

        $tasks_examine = DB::table('tasks_examine as a')
            ->leftJoin('users as b','a.user_id','=','b.Id')
            ->whereIn('task_id', $task_id)
            ->select('a.state','b.account as user_examine','a.task_id')
            ->get()
            ->toArray();

        $notExamine = [];
        $ExamineOk = [];
        $ExamineNo = [];
        foreach ($tasks_examine as $te){
            if($te->state==1||$te->state==2){
                $notExamine[$te->task_id][] = $te->user_examine;
            }elseif($te->state==3){
                $ExamineOk[$te->task_id][] = $te->user_examine;
            }elseif($te->state==4){
                $ExamineNo[$te->task_id][] = $te->user_examine;
            }
        }

        $tasks_news = DB::table('tasks_news as a')
            ->select('a.task_id', 'b.account as user_fs', 'c.account as user_js', 'a.content', 'a.create_time')
            ->leftjoin('users as b', 'b.Id', '=', 'a.user_fs')
            ->leftjoin('users as c', 'c.Id', '=', 'a.user_js')
            ->whereIn('task_id', $task_id)
            ->get();
        $tasks_news = json_decode(json_encode($tasks_news), true);
        $shop = Db::table('shop')->select('Id', 'shop_name', 'country_id')->get()->toArray();
        $plan_status = Db::table('amazon_plan_status')->get()->toArray();
        $base = new BaseModel();
        $billMdl = db::table('financial_bill')
            ->get()
            ->keyBy('id');
        $contractMdl = db::table('cloudhouse_contract_total')
            ->get()
            ->keyBy('contract_no');

        $contractSpuMdl = db::table('cloudhouse_contract')
            ->select('contract_no', 'one_price', db::raw('group_concat(spu SEPARATOR ",") as spu'), db::raw('group_concat(spu_id SEPARATOR ",") as spu_id'))
            ->groupBy('contract_no')
            ->get()
            ->keyBy('contract_no');
        foreach ($list as &$item) {
            foreach ($tasks_news as $k => $v) {
                if ($item['Id'] == $v['task_id']) {
                    $item['tasks_news'][] = $v;
                }
            }

            if(isset($notExamine[$item['Id']])){
                $item['not_examine'] = $notExamine[$item['Id']];
            }else{
                $item['not_examine'] = [];
            }

            if(isset($ExamineOk[$item['Id']])){
                $item['examine_ok'] = $ExamineOk[$item['Id']];
            }else{
                $item['examine_ok'] = [];
            }

            if(isset($ExamineNo[$item['Id']])){
                $item['examine_no'] = $ExamineNo[$item['Id']];
            }else{
                $item['examine_no'] = [];
            }
            $item['sku_count'] = 0;
            $item['sum'] = 0;
            $item['spulist'] = [];
            $item['father_asin'] = [];
            $item['father_asin_info'] = [];
            if ($item['ext'] != null && $item['ext'] != '') {
                $ext = json_decode($item['ext'], true);
                $item['ext'] = $ext;
                $TaskClassModule = TaskClassModule::where('class_id', $item['class_id'])->get()->toArray();
                $item['clsss_module'] = $TaskClassModule;
                if (isset($ext['request_id'])) {
                    $detail = DB::table('amazon_buhuo_detail')->where('request_id', '=', $ext['request_id'])->select('id')->get();
                    $item['sku_count'] = count($detail);
                }
                if (isset($ext['start_time'])) {
                    $item['start_time'] = $ext['start_time'];
                }
                if (isset($ext['end_time'])) {
                    $item['end_time'] = $ext['end_time'];
                }
                if (isset($ext['request_link'])) {
                    $item['request_link'] = $ext['request_link'];
                }
                if (isset($ext['request_id'])) {
                    $item['request_id'] = $ext['request_id'];

                    $sql = "SELECT   a.request_num, a.transportation_mode_name, a.transportation_type, c.shop_id, c.transportation_date,b.fasin,c.request_status
                FROM
                    amazon_buhuo_detail a 
                LEFT JOIN self_sku b ON a.sku_id = b.id
                LEFT JOIN amazon_buhuo_request c ON a.request_id = c.id
                WHERE
                    request_id='" . $item['request_id'] . "'
                ORDER BY
                    a.custom_sku desc";
                    $data = DB::select($sql);
                    $item['shop_name'] = '';
                    $item['transport_type'] = '';
                    $item['request_status'] = '';
                    $item['transport_date'] = '';
                    $sum = 0;
                    $father_asin = [];
                    foreach ($data as $val) {
                        if ($val->fasin != '' || $val->fasin != null) {
                            $father_asin[] = $val->fasin;
                        }
                        $sum = $sum + $val->request_num;
                        $shop_arr = $base->GetShop($val->shop_id);
                        $item['shop_name'] = $shop_arr['account'];
                        $item['country_id'] = $shop_arr['country_id'];
                        $item['shop_id'] = $val->shop_id;
                        $request_status = $val->request_status;
                        $item['request_status'] = $base->GetPlan($request_status)['status_name'];

                        $item['transport_type'] = $val->transportation_mode_name;
                        $item['transport_date'] = date('Y-m-d', strtotime($val->transportation_date));
                    }
                    $item['father_asin'] = array_unique($father_asin);
                    $item['sum'] = $sum;
                }

                if(isset($ext['request_id'])){

                    $order = db::table('amazon_buhuo_detail')->where('request_id',$ext['request_id'])->get()->toarray();
                    if($order){
                        $sku_ids = array_unique(array_column($order,'sku_id'));
                        $spu_ids = array_unique(array_column($order,'spu_id'));
                        $spus = array_unique(array_column($order,'spu'));
                        $spu_with_id = array_unique(array_column($order,'spu','spu_id'));
                        foreach ($spus as $sp){
                            $item['spulist'][]['spu'] = $sp;
                        }

                        $skures = db::table('self_sku')->whereIn('id',$sku_ids)->get()->toarray();
                        $father_asin = array_unique(array_column($skures,'fasin'));
                        if(isset($father_asin)){
                            //查询周转天数
                            $inventory_days = db::table('inventory_day_fasin')->whereIn('fasin',$father_asin)->get();
                            $new_fasin = [];
                            foreach ($inventory_days as $fav) {
                                # code...
                                $new_fasin[$fav->fasin]['fasin'] = $fav->fasin;
                                if($order[0]->shop_id>0){
                                    $new_fasin[$fav->fasin]['fasin_code'] = db::table('amazon_fasin_bind')->where('fasin',$fav->fasin)->where('shop_id',$order[0]->shop_id)->first()->fasin_code;
                                }else{
                                    $new_fasin[$fav->fasin]['fasin_code'] = '';
                                }
                                if($fav->find_day==7){
                                    $new_fasin[$fav->fasin]['w_fba_days']= $fav->fba_days;
                                    $new_fasin[$fav->fasin]['w_here_days']= $fav->here_days;
                                }
                                if($fav->find_day==30){
                                    $new_fasin[$fav->fasin]['m_fba_days']= $fav->fba_days;
                                    $new_fasin[$fav->fasin]['m_here_days']= $fav->here_days;
                                }
                                if($fav->find_day==90){
                                    $new_fasin[$fav->fasin]['tm_fba_days']= $fav->fba_days;
                                    $new_fasin[$fav->fasin]['tm_here_days']= $fav->here_days;
                                }
                               
                            }
    
                            $new_fasin_b = [];
                            foreach ($father_asin as $faav) {
                                # code...
                                if(isset($new_fasin[$faav])){
                                    $new_fasin_b[] = $new_fasin[$faav];
                                }else{
                                    $new_fasin_b[] = ["fasin"=>$faav,'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                                }
                               
                            }
                            $item['father_asin'] = $father_asin;
                            $item['father_asin_info'] = $new_fasin_b;
    
                        }
    
    
                        if(!empty($spu_ids)){
    
                          
                            //查询周转天数
                            $spu_inventory_days = db::table('inventory_day_spu')->whereIn('spu_id',$spu_ids)->get();
                            $new_spus = [];
                            foreach ($spu_inventory_days as $spav) {
                                # code...
                                $new_spus[$spav->spu_id]['spu_id'] = $spav->spu_id;
                                $new_spus[$spav->spu_id]['spu'] = $spu_with_id[$spav->spu_id];
                                if($spav->find_day==7){
                                    $new_spus[$spav->spu_id]['w_fba_days']= $spav->fba_days;
                                    $new_spus[$spav->spu_id]['w_here_days']= $spav->here_days;
                                }
                                if($spav->find_day==30){
                                    $new_spus[$spav->spu_id]['m_fba_days']= $spav->fba_days;
                                    $new_spus[$spav->spu_id]['m_here_days']= $spav->here_days;
                                }
                                if($spav->find_day==90){
                                    $new_spus[$spav->spu_id]['tm_fba_days']= $spav->fba_days;
                                    $new_spus[$spav->spu_id]['tm_here_days']= $spav->here_days;
                                }
                               
                            }
    
                            $new_spus_b = [];
                            foreach ($spu_ids as $spaav) {
                                # code...
                                if(isset($new_spus[$spaav])){
                                    $new_spus_b[] = $new_spus[$spaav];
                                }else{
                                    $new_spus_b[] = ["spu_id"=>$spaav,"spu"=>$spu_with_id[$spaav],'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                                }
                               
                            }
                            $item['spu_info'] = $new_spus_b;
    
                        }


                    }

                }

                if(isset($ext['order_id'])){
                    $order = DB::table('amazon_place_order_task')->where('id', '=', $ext['order_id'])->select('order_num','shop_id','spulist','status','mode','one_ids','platform_id')->first();
                    $order = json_decode(json_encode($order),true);

                    if($order['mode']==1){
                        $one_ids = explode(',',$order['one_ids']);
                        foreach ($one_ids as $i){
                            $task_one = DB::table('amazon_team_task_one')->where('id',$i)->select('shop_id')->first();
                            if (empty($task_one)){
                                continue;
                            }
                            $task_detail = DB::table('amazon_team_task_detail')->where('order_id',$i)->select('custom_sku_id','order_num','suppliers_price','spu_id','spu')->get();
                            $task_detail = json_decode(json_encode($task_detail),true);
                            $total_price = 0;
                            $spu_price = [];
                            foreach ($task_detail as $td){
                                if(!isset($spu_price[$td['spu_id']])){
                                    $spu_price[$td['spu_id']] = $td['suppliers_price'];
                                }
                                $custom_sku_idList[] = $td['custom_sku_id'];
                                $orderNum = json_decode($td['order_num'],true);
                                $orderNumSum = array_sum($orderNum);
                                $total_price += $orderNumSum*$td['suppliers_price'];
                            }
                            $asinlist = DB::table('self_sku')->where('shop_id',$task_one->shop_id)->whereIn('custom_sku_id',$custom_sku_idList)->select('fasin')->distinct()->get();
                            if(!empty($asinlist)){
                                foreach ($asinlist as $as){
                                    if ($as->fasin != '' ||  $as->fasin != null){
                                        $father_asin[] = $as->fasin;
                                    }
                                }
                            }
                        }
                    }
                    if($order['mode']==2){
                        $task_detail =  DB::table('amazon_place_order_detail')->where('order_id',$ext['order_id'])->select('custom_sku_id','order_num','suppliers_price','spu_id','spu')->get();
                        $task_detail = json_decode(json_encode($task_detail),true);
                        $custom_sku_idList = [];
                        $total_price = 0;
                        foreach ($task_detail as $td){
                            if(!isset($spu_price[$td['spu_id']])){
                                $spu_price[$td['spu_id']] = $td['suppliers_price'];
                            }
                            $custom_sku_idList[] = $td['custom_sku_id'];
                            $orderNum = json_decode($td['order_num'],true);
                            $orderNumSum = array_sum($orderNum);
                            $total_price += $orderNumSum*$td['suppliers_price'];
                        }
                        $asinlist = DB::table('self_sku')->where('shop_id',$order['shop_id'])->whereIn('custom_sku_id',$custom_sku_idList)->select('fasin')->distinct()->get();
                        if(!empty($asinlist)){
                            foreach ($asinlist as $as){
                                if ($as->fasin != '' ||  $as->fasin != null){
                                    $father_asin[] = $as->fasin;
                                }
                            }
                        }
                    }
                    $spu_list = explode(',',$order['spulist']);
                    foreach ($spu_list as $sk=>$sp){
                        $item['spulist'][$sk]['spu'] = $sp;
                        $thisSpuId = $base->GetSpuId($sp);
                        $item['spulist'][$sk]['one_price'] = '未知价格';
                        if(isset($spu_price[$thisSpuId])){
                            $item['spulist'][$sk]['one_price'] = $spu_price[$thisSpuId];
                        }
                    }
                    $item['sum'] = $order['order_num'];
                    $item['task_status'] = $order['status'];
                    $shop = $base->GetShop($order['shop_id']);
                    $item['shop_name'] = $shop['account'];
                    $item['country_id'] = $shop['country_id'];
                    $item['father_asin'] = [];
                    $item['shop_id'] = $order['shop_id'];
                    $item['platform_name'] = '';
                    $item['total_price'] = isset($total_price)? round($total_price,2):0;
                    $item['one_price'] = round($item['total_price']/$item['sum'],2);
                    if($order['platform_id']>0){
                        $item['platform_name'] = db::table('platform')->where('Id',$order['platform_id'])->select('name')->first()->name??'';
                    }
                    if(isset($father_asin)){

                        $father_asin = array_unique($father_asin);
                        //查询周转天数
                        $inventory_days = db::table('inventory_day_fasin')->whereIn('fasin',$father_asin)->get();
                        $new_fasin = [];
                        foreach ($inventory_days as $fav) {
                            # code...
                            $new_fasin[$fav->fasin]['fasin'] = $fav->fasin;
                            if($item['shop_id']>0){
                                $fasin_codes =  db::table('amazon_fasin_bind')->where('fasin',$fav->fasin)->where('shop_id',$item['shop_id'])->first();
                                if($fasin_codes){
                                    $new_fasin[$fav->fasin]['fasin_code'] =$fasin_codes->fasin_code;
                                }else{
                                    $new_fasin[$fav->fasin]['fasin_code'] = '';
                                }
                               
                            }else{
                                $new_fasin[$fav->fasin]['fasin_code'] = '';
                            }
                            if($fav->find_day==7){
                                $new_fasin[$fav->fasin]['w_fba_days']= $fav->fba_days;
                                $new_fasin[$fav->fasin]['w_here_days']= $fav->here_days;
                            }
                            if($fav->find_day==30){
                                $new_fasin[$fav->fasin]['m_fba_days']= $fav->fba_days;
                                $new_fasin[$fav->fasin]['m_here_days']= $fav->here_days;
                            }
                            if($fav->find_day==90){
                                $new_fasin[$fav->fasin]['tm_fba_days']= $fav->fba_days;
                                $new_fasin[$fav->fasin]['tm_here_days']= $fav->here_days;
                            }
                           
                        }

                        $new_fasin_b = [];
                        foreach ($father_asin as $faav) {
                            # code...
                            if(isset($new_fasin[$faav])){
                                $new_fasin_b[] = $new_fasin[$faav];
                            }else{
                                $new_fasin_b[] = ["fasin"=>$faav,'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                            }
                           
                        }
                        $item['father_asin'] = $father_asin;
                        $item['father_asin_info'] = $new_fasin_b;

                    }


                    if(isset($order['spulist'])){

                        $spu_list_ids = [];
                        $spu_with_id = [];
                        foreach ($spu_list as $spuone) {
                            # code...
                            $spu_id = db::table('self_spu')->where('spu',$spuone)->orwhere('old_spu',$spuone)->first();
                            if($spu_id){
                                $spu_list_ids[] = $spu_id->id;
                                $spu_with_id[$spu_id->id] = $spuone;
                            } 
                        }
                        //查询周转天数
                        $spu_inventory_days = db::table('inventory_day_spu')->whereIn('spu_id',$spu_list_ids)->get();
                        $new_spus = [];
                        foreach ($spu_inventory_days as $spav) {
                            # code...
                            $new_spus[$spav->spu_id]['spu_id'] = $spav->spu_id;
                            $new_spus[$spav->spu_id]['spu'] = $spu_with_id[$spav->spu_id];
                            if($spav->find_day==7){
                                $new_spus[$spav->spu_id]['w_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['w_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==30){
                                $new_spus[$spav->spu_id]['m_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['m_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==90){
                                $new_spus[$spav->spu_id]['tm_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['tm_here_days']= $spav->here_days;
                            }
                           
                        }

                        $new_spus_b = [];
                        foreach ($spu_list_ids as $spaav) {
                            # code...
                            if(isset($new_spus[$spaav])){
                                $new_spus_b[] = $new_spus[$spaav];
                            }else{
                                $new_spus_b[] = ["spu_id"=>$spaav,"spu"=>$spu_with_id[$spaav],'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                            }
                           
                        }
                        $item['spu_info'] = $new_spus_b;

                    }

    
     


                }

                if(isset($ext['transfers_id'])){
                    $goods_transfers = DB::table('goods_transfers')->where('order_no',$ext['transfers_id'])->select('platform_id')->first();
                    $item['platform_name'] = '';
                    if(!empty($goods_transfers)){
                        if($goods_transfers->platform_id>0){
                            $item['platform_name'] = db::table('platform')->where('Id',$goods_transfers->platform_id)->select('name')->first()->name??'';
                        }

                    }
                }

                $fasinCode = [];
                $fasin_v_code = [];
                if (isset($item['father_asin'])){
                    foreach ($item['father_asin'] as $fasin){
                        $fasinCodeMdl = $base->GetFasinCodeNew($fasin, $item['shop_id']);
//                        if ($token == '660B08F029946C65247AC7204F1C5A72'){
//                            var_dump($fasin);
//                            var_dump($item['shop_id']);
//                            var_dump($fasinCodeMdl);
//                        }
                        if ($item['shop_id']){
                            if (!empty($fasinCodeMdl)){
                                $fasin_v_code[$fasin] = $fasinCodeMdl['fasin_code'];
                                $fasinCode[] = $fasinCodeMdl['fasin_code'] ?? '';
                            }
                        }
                    }
                    $item['fasin_code'] = $fasinCode;
                }
//                 if(isset($ext['order_id'])){
//                     $order = DB::table('amazon_place_order_task')->where('id', '=', $ext['order_id'])->select('order_num','shop_id','spulist','status')->first();
//                     $order = json_decode(json_encode($order),true);
// //                    $item['sku_count'] = $order->sku_count;
//                     $item['sum'] = $order['order_num'];
//                     $item['spulist'] = $order['spulist'];
//                     $item['task_status'] = $order['status'];
//                     $shop = $base->GetShop($order['shop_id']);
//                     $item['shop_name'] = $shop['account'];
//                     $item['shop_id'] = $order['shop_id'];
//                 }

                if(!empty($item['shop_id'])){
                    $shop_id = $item['shop_id'];
                    $shop_arr = $base->GetShop($shop_id);
                    $item['shop_name'] = $shop_arr['account'];
                    $item['country_id'] = $shop_arr['country_id'];
//                    $shop_arr = array_filter($shop, function ($t) use ($shop_id) {
//                        return $t->Id == $shop_id;
//                    });
//                    $item['country_id'] = array_column($shop_arr, 'country_id')[0];
//                    $item['shop_name'] = array_column($shop_arr, 'shop_name')[0];
                }

                $item['is_print_pdf'] = '未打印';
                if (isset($ext['contract_no'])){
                    $contract = $contractMdl[$ext['contract_no']] ?? [];
                    $contractSpu = $contractSpuMdl[$ext['contract_no']] ?? [];
                    $item['is_print_pdf'] = isset($contract->is_print_pdf)&&$contract->is_print_pdf == 1 ? '已打印' : '未打印';
                    $spuList = array_unique(explode(',', $contractSpu->spu ?? ''));
                    foreach ($spuList as $sp){
                        $item['spulist'][]['spu'] = $sp;
                    }

                    $item['ext']['supplier_name'] = $contract->supplier_short_name ?? '';
                    $item['ext']['company_name'] = $contract->company_name ?? '';
                    // 逆天啊
                    $item['clsss_module'][] = [
                        'id' => 0,
                        'label' => '供应商名称',
                        'name' => 'supplier_name',
                        'type' => 1,
                        'api' => '',
                        'class_id' => 0,
                        'api_id' => 0,
                        'api_label' => '',
                        'api_param' => []
                    ];
                    $item['clsss_module'][] = [
                        'id' => 0,
                        'label' => '公司抬头',
                        'name' => 'company_name',
                        'type' => 1,
                        'api' => '',
                        'class_id' => 0,
                        'api_id' => 0,
                        'api_label' => '',
                        'api_param' => []
                    ];
                    if(isset($spuList) && !empty($spuList)){
                        $spu_list_ids = [];
                        $spu_with_id = [];
                        foreach ($spuList as $spuone) {
                            # code...
                            $spu_id = db::table('self_spu')->where('spu',$spuone)->orwhere('old_spu',$spuone)->first();
                            if($spu_id){
                                $spu_list_ids[] = $spu_id->id;
                                $spu_with_id[$spu_id->id] = $spuone;
                            }
                        }
                        //查询周转天数
                        $spu_inventory_days = db::table('inventory_day_spu')->whereIn('spu_id',$spu_list_ids)->get();
                        $new_spus = [];
                        foreach ($spu_inventory_days as $spav) {
                            # code...
                            $new_spus[$spav->spu_id]['spu_id'] = $spav->spu_id;
                            $new_spus[$spav->spu_id]['spu'] = $spu_with_id[$spav->spu_id];
                            if($spav->find_day==7){
                                $new_spus[$spav->spu_id]['w_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['w_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==30){
                                $new_spus[$spav->spu_id]['m_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['m_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==90){
                                $new_spus[$spav->spu_id]['tm_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['tm_here_days']= $spav->here_days;
                            }

                        }

                        $new_spus_b = [];
                        foreach ($spu_list_ids as $spaav) {
                            # code...
                            if(isset($new_spus[$spaav])){
                                $new_spus_b[] = $new_spus[$spaav];
                            }else{
                                $new_spus_b[] = ["spu_id"=>$spaav,"spu"=>$spu_with_id[$spaav],'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                            }

                        }
                        $item['spu_info'] = $new_spus_b;

                    }
                }

            }
        }

        $return['list'] = $list;
        return $return;
    }

    /**
     * 待验收的任务
     */
    public function task_me_acceptance($data)
    {
        $where = "t.state=4 and t.type=1";

        if (!empty($data['user_id'])) {
            $where .= " and t.`user_cj`={$data['user_id']}";
        } else {
            $where .= " and t.`user_cj`=0";
        }
        //name 任务名称
        if (isset($data['name'])) {
            $where .= " and t.`name` like '%{$data['name']}%'";
        }
        //user_fz_name 负责人名称
        if (isset($data['user_fz_name'])) {
            $where .= " and u_fz.`account` like '%{$data['user_fz_name']}%'";
        }
        //task_keys 任务详情
        if (isset($data['task_keys'])) {
            $where .= " and t.`ext` like '%{$data['task_keys']}%'";
        }
        //class_id 任务分类
        if (isset($data['class_id'])) {
            $classArr = implode(',',$data['class_id']);
            $where .= " and t.`class_id` in ($classArr)";
        }
        if (isset($data['task_id'])) {
            $where .= " and t.`Id`={$data['task_id']}";
        }
        //create_time 创建时间
        if (!empty($data['create_time'])) {
            $state_time = $data['create_time'][0] . ' 00:00:00';
            $end_time = $data['create_time'][1] . ' 23:59:59';
            $where .= " and t.create_time>='{$state_time}' and t.create_time<='{$end_time}'";
        }

        $limit = "";
        if ((!empty($data['page'])) and (!empty($data['page_count']))) {
            $limit = " limit " . ($data['page'] - 1) * $data['page_count'] . ",{$data['page_count']}";
        }

        $sql = "select SQL_CALC_FOUND_ROWS t.*, u_fz.account as account_fz, u_cj.account as account_cj
				       from tasks t
				       inner join users u_fz on u_fz.Id = t.user_fz
				       inner join users u_cj on u_cj.Id = t.user_cj
				       where {$where}
				       order by t.create_time asc {$limit}";
        $list = json_decode(json_encode(db::select($sql)), true);

        //// 总条数
        if (isset($data['page']) and isset($data['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }

        if (empty($list)) {
            $return['list'] = [];
            return $return;
        }
        $task_id = array_column($list, 'Id');

        $tasks_examine = DB::table('tasks_examine as a')
            ->leftJoin('users as b','a.user_id','=','b.Id')
            ->whereIn('task_id', $task_id)
            ->select('a.state','b.account as user_examine','a.task_id')
            ->get()
            ->toArray();

        $notExamine = [];
        $ExamineOk = [];
        $ExamineNo = [];
        foreach ($tasks_examine as $te){
            if($te->state==1||$te->state==2){
                $notExamine[$te->task_id][] = $te->user_examine;
            }elseif($te->state==3){
                $ExamineOk[$te->task_id][] = $te->user_examine;
            }elseif($te->state==4){
                $ExamineNo[$te->task_id][] = $te->user_examine;
            }
        }

        $tasks_news = DB::table('tasks_news as a')
            ->select('a.task_id', 'b.account as user_fs', 'c.account as user_js', 'a.content', 'a.create_time')
            ->leftjoin('users as b', 'b.Id', '=', 'a.user_fs')
            ->leftjoin('users as c', 'c.Id', '=', 'a.user_js')
            ->whereIn('task_id', $task_id)
            ->get();
        $tasks_news = json_decode(json_encode($tasks_news), true);
        $shop = Db::table('shop')->select('Id', 'shop_name', 'country_id')->get()->toArray();
        $plan_status = Db::table('amazon_plan_status')->get()->toArray();
        $base = new BaseModel();
        foreach ($list as &$item) {
            foreach ($tasks_news as $k => $v) {
                if ($item['Id'] == $v['task_id']) {
                    $item['tasks_news'][] = $v;
                }
            }

            if(isset($notExamine[$item['Id']])){
                $item['not_examine'] = $notExamine[$item['Id']];
            }else{
                $item['not_examine'] = [];
            }

            if(isset($ExamineOk[$item['Id']])){
                $item['examine_ok'] = $ExamineOk[$item['Id']];
            }else{
                $item['examine_ok'] = [];
            }

            if(isset($ExamineNo[$item['Id']])){
                $item['examine_no'] = $ExamineNo[$item['Id']];
            }else{
                $item['examine_no'] = [];
            }
            
            $item['sku_count'] = 0;
            $item['sum'] = 0;
            if ($item['ext'] != null && $item['ext'] != '') {
                $ext = json_decode($item['ext'], true);
                $item['ext'] = $ext;
                $TaskClassModule = TaskClassModule::where('class_id', $item['class_id'])->get()->toArray();
                $item['clsss_module'] = $TaskClassModule;
                if (isset($ext['request_id'])) {
                    $detail = DB::table('amazon_buhuo_detail')->where('request_id', '=', $ext['request_id'])->select('id')->get();
                    $item['sku_count'] = count($detail);
                }
                if (isset($ext['start_time'])) {
                    $item['start_time'] = $ext['start_time'];
                }
                if (isset($ext['end_time'])) {
                    $item['end_time'] = $ext['end_time'];
                }
                if (isset($ext['request_link'])) {
                    $item['request_link'] = $ext['request_link'];
                }
                if (isset($ext['request_id'])) {
                    $item['request_id'] = $ext['request_id'];

                    $sql = "SELECT  a.request_num, a.transportation_mode_name, a.transportation_type, c.shop_id, c.courier_date, c.shipping_date, c.air_date ,b.parent_asin,c.request_status
                FROM
                    amazon_buhuo_detail a 
                LEFT JOIN self_sku b ON a.sku_id = b.id
                LEFT JOIN amazon_buhuo_request c ON a.request_id = c.id
                WHERE
                    request_id='" . $item['request_id'] . "'
                ORDER BY
                    a.custom_sku desc";
                    $data = DB::select($sql);
                    $item['shop_name'] = '';
                    $item['transport_type'] = '';
                    $item['request_status'] = '';
                    $sum = 0;
                    $father_asin = [];
                    foreach ($data as $val) {
                        if ($val->fasin != '' || $val->fasin != null) {
                            $father_asin[] = $val->fasin;
                        }
                        $sum = $sum + $val->request_num;

                        $shop_arr = $base->GetShop($val->shop_id);
                        $item['shop_name'] = $shop_arr['account'];
                        $item['country_id'] = $shop_arr['country_id'];
                        $item['shop_id'] = $val->shop_id;

                        $request_status = $val->request_status;
//                        $plan_arr = array_filter($plan_status, function ($t) use ($request_status) {
//                            return $t->id == $request_status;
//                        });
//                        $item['request_status'] = array_column($plan_arr,'status_name')[0];
                        $item['request_status'] = $base->GetPlan($request_status)['status_name'];
                        $item['transport_type'] = $val->transportation_mode_name ?? '';
                    }
                    $item['father_asin'] = array_unique($father_asin);
                    $item['sum'] = $sum;
                }



                if(isset($ext['request_id'])){

                    $order = db::table('amazon_buhuo_detail')->where('request_id',$ext['request_id'])->get()->toarray();
                    if($order){
                        $sku_ids = array_unique(array_column($order,'sku_id'));
                        $spu_ids = array_unique(array_column($order,'spu_id'));
                        $spus = array_unique(array_column($order,'spu'));
                        $spu_with_id = array_unique(array_column($order,'spu','spu_id'));
                        foreach ($spus as $sp){
                            $item['spulist'][]['spu'] = $sp;
                        }
                        $skures = db::table('self_sku')->whereIn('id',$sku_ids)->get()->toarray();
                        $father_asin = array_unique(array_column($skures,'fasin'));
                        if(isset($father_asin)){
                            //查询周转天数
                            $inventory_days = db::table('inventory_day_fasin')->whereIn('fasin',$father_asin)->get();
                            $new_fasin = [];
                            foreach ($inventory_days as $fav) {
                                # code...
                                $new_fasin[$fav->fasin]['fasin'] = $fav->fasin;
                                if($order[0]->shop_id>0){
                                    $new_fasin[$fav->fasin]['fasin_code'] = db::table('amazon_fasin_bind')->where('fasin',$fav->fasin)->where('shop_id',$order[0]->shop_id)->first()->fasin_code;
                                }else{
                                    $new_fasin[$fav->fasin]['fasin_code'] = '';
                                }
                                if($fav->find_day==7){
                                    $new_fasin[$fav->fasin]['w_fba_days']= $fav->fba_days;
                                    $new_fasin[$fav->fasin]['w_here_days']= $fav->here_days;
                                }
                                if($fav->find_day==30){
                                    $new_fasin[$fav->fasin]['m_fba_days']= $fav->fba_days;
                                    $new_fasin[$fav->fasin]['m_here_days']= $fav->here_days;
                                }
                                if($fav->find_day==90){
                                    $new_fasin[$fav->fasin]['tm_fba_days']= $fav->fba_days;
                                    $new_fasin[$fav->fasin]['tm_here_days']= $fav->here_days;
                                }
                            
                            }

                            $new_fasin_b = [];
                            foreach ($father_asin as $faav) {
                                # code...
                                if(isset($new_fasin[$faav])){
                                    $new_fasin_b[] = $new_fasin[$faav];
                                }else{
                                    $new_fasin_b[] = ["fasin"=>$faav,'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                                }
                            
                            }
                            $item['father_asin'] = $father_asin;
                            $item['father_asin_info'] = $new_fasin_b;

                        }


                        if(!empty($spu_ids)){

                        
                            //查询周转天数
                            $spu_inventory_days = db::table('inventory_day_spu')->whereIn('spu_id',$spu_ids)->get();
                            $new_spus = [];
                            foreach ($spu_inventory_days as $spav) {
                                # code...
                                $new_spus[$spav->spu_id]['spu_id'] = $spav->spu_id;
                                $new_spus[$spav->spu_id]['spu'] = $spu_with_id[$spav->spu_id];
                                if($spav->find_day==7){
                                    $new_spus[$spav->spu_id]['w_fba_days']= $spav->fba_days;
                                    $new_spus[$spav->spu_id]['w_here_days']= $spav->here_days;
                                }
                                if($spav->find_day==30){
                                    $new_spus[$spav->spu_id]['m_fba_days']= $spav->fba_days;
                                    $new_spus[$spav->spu_id]['m_here_days']= $spav->here_days;
                                }
                                if($spav->find_day==90){
                                    $new_spus[$spav->spu_id]['tm_fba_days']= $spav->fba_days;
                                    $new_spus[$spav->spu_id]['tm_here_days']= $spav->here_days;
                                }
                            
                            }

                            $new_spus_b = [];
                            foreach ($spu_ids as $spaav) {
                                # code...
                                if(isset($new_spus[$spaav])){
                                    $new_spus_b[] = $new_spus[$spaav];
                                }else{
                                    $new_spus_b[] = ["spu_id"=>$spaav,"spu"=>$spu_with_id[$spaav],'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                                }
                            
                            }
                            $item['spu_info'] = $new_spus_b;

                        }


                    }




                }

                if(isset($ext['order_id'])){
                    $order = DB::table('amazon_place_order_task')->where('id', '=', $ext['order_id'])->select('order_num','shop_id','spulist','status','mode','one_ids','platform_id')->first();
                    $order = json_decode(json_encode($order),true);

                    if($order['mode']==1){
                        $one_ids = explode(',',$order['one_ids']);
                        foreach ($one_ids as $i){
                            $task_one = DB::table('amazon_team_task_one')->where('id',$i)->select('shop_id')->first();
                            if (empty($task_one)){
                                continue;
                            }
                            $task_detail = DB::table('amazon_team_task_detail')->where('order_id',$i)->select('custom_sku_id','order_num','suppliers_price','spu_id','spu')->get();
                            $task_detail = json_decode(json_encode($task_detail),true);
                            $total_price = 0;
                            $spu_price = [];
                            foreach ($task_detail as $td){
                                if(!isset($spu_price[$td['spu_id']])){
                                    $spu_price[$td['spu_id']] = $td['suppliers_price'];
                                }
                                $custom_sku_idList[] = $td['custom_sku_id'];
                                $orderNum = json_decode($td['order_num'],true);
                                $orderNumSum = array_sum($orderNum);
                                $total_price += $orderNumSum*$td['suppliers_price'];
                            }
                            $asinlist = DB::table('self_sku')->where('shop_id',$task_one->shop_id)->whereIn('custom_sku_id',$custom_sku_idList)->select('fasin')->distinct()->get();
                            if(!empty($asinlist)){
                                foreach ($asinlist as $as){
                                    if ($as->fasin != '' ||  $as->fasin != null){
                                        $father_asin[] = $as->fasin;
                                    }
                                }
                            }
                        }
                    }
                    if($order['mode']==2){
                        $task_detail =  DB::table('amazon_place_order_detail')->where('order_id',$ext['order_id'])->select('custom_sku_id','order_num','suppliers_price','spu_id','spu')->get();
                        $task_detail = json_decode(json_encode($task_detail),true);
                        $custom_sku_idList = [];
                        $total_price = 0;
                        foreach ($task_detail as $td){
                            if(!isset($spu_price[$td['spu_id']])){
                                $spu_price[$td['spu_id']] = $td['suppliers_price'];
                            }
                            $custom_sku_idList[] = $td['custom_sku_id'];
                            $orderNum = json_decode($td['order_num'],true);
                            $orderNumSum = array_sum($orderNum);
                            $total_price += $orderNumSum*$td['suppliers_price'];
                        }
                        $asinlist = DB::table('self_sku')->where('shop_id',$order['shop_id'])->whereIn('custom_sku_id',$custom_sku_idList)->select('fasin')->distinct()->get();
                        if(!empty($asinlist)){
                            foreach ($asinlist as $as){
                                if ($as->fasin != '' ||  $as->fasin != null){
                                    $father_asin[] = $as->fasin;
                                }
                            }
                        }
                    }
                    $spu_list = explode(',',$order['spulist']);
                    foreach ($spu_list as $sk=>$sp){
                        $item['spulist'][$sk]['spu'] = $sp;
                        $thisSpuId = $base->GetSpuId($sp);
                        $item['spulist'][$sk]['one_price'] = '未知价格';
                        if(isset($spu_price[$thisSpuId])){
                            $item['spulist'][$sk]['one_price'] = $spu_price[$thisSpuId];
                        }
                    }
                    $item['sum'] = $order['order_num'];
                    $item['task_status'] = $order['status'];
                    $shop = $base->GetShop($order['shop_id']);
                    $item['shop_name'] = $shop['account'];
                    $item['country_id'] = $shop['country_id'];
                    $item['father_asin'] = [];
                    $item['shop_id'] = $order['shop_id'];
                    $item['platform_name'] = '';
                    $item['total_price'] = isset($total_price)? round($total_price,2):0;
                    $item['one_price'] = round($item['total_price']/$item['sum'],2);
                    if($order['platform_id']>0){
                        $item['platform_name'] = db::table('platform')->where('Id',$order['platform_id'])->select('name')->first()->name??'';
                    }
                    if(isset($father_asin)){

                        $father_asin = array_unique($father_asin);
                        //查询周转天数
                        $inventory_days = db::table('inventory_day_fasin')->whereIn('fasin',$father_asin)->get();
                        $new_fasin = [];
                        foreach ($inventory_days as $fav) {
                            # code...
                            $new_fasin[$fav->fasin]['fasin'] = $fav->fasin;
                            if($item['shop_id']>0){
                                $fasin_codes =  db::table('amazon_fasin_bind')->where('fasin',$fav->fasin)->where('shop_id',$item['shop_id'])->first();
                                if($fasin_codes){
                                    $new_fasin[$fav->fasin]['fasin_code'] =$fasin_codes->fasin_code;
                                }else{
                                    $new_fasin[$fav->fasin]['fasin_code'] = '';
                                }
                               
                            }else{
                                $new_fasin[$fav->fasin]['fasin_code'] = '';
                            }
                            if($fav->find_day==7){
                                $new_fasin[$fav->fasin]['w_fba_days']= $fav->fba_days;
                                $new_fasin[$fav->fasin]['w_here_days']= $fav->here_days;
                            }
                            if($fav->find_day==30){
                                $new_fasin[$fav->fasin]['m_fba_days']= $fav->fba_days;
                                $new_fasin[$fav->fasin]['m_here_days']= $fav->here_days;
                            }
                            if($fav->find_day==90){
                                $new_fasin[$fav->fasin]['tm_fba_days']= $fav->fba_days;
                                $new_fasin[$fav->fasin]['tm_here_days']= $fav->here_days;
                            }
                        
                        }

                        $new_fasin_b = [];
                        foreach ($father_asin as $faav) {
                            # code...
                            if(isset($new_fasin[$faav])){
                                $new_fasin_b[] = $new_fasin[$faav];
                            }else{
                                $new_fasin_b[] = ["fasin"=>$faav,'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                            }
                        
                        }
                        $item['father_asin'] = $father_asin;
                        $item['father_asin_info'] = $new_fasin_b;

                    }


                    if(isset($order['spulist'])){
                        $spu_list_ids = [];
                        $spu_with_id = [];
                        foreach ($spu_list as $spuone) {
                            # code...
                            $spu_id = db::table('self_spu')->where('spu',$spuone)->orwhere('old_spu',$spuone)->first();
                            if($spu_id){
                                $spu_list_ids[] = $spu_id->id;
                                $spu_with_id[$spu_id->id] = $spuone;
                            } 
                        }
                        //查询周转天数
                        $spu_inventory_days = db::table('inventory_day_spu')->whereIn('spu_id',$spu_list_ids)->get();
                        $new_spus = [];
                        foreach ($spu_inventory_days as $spav) {
                            # code...
                            $new_spus[$spav->spu_id]['spu_id'] = $spav->spu_id;
                            $new_spus[$spav->spu_id]['spu'] = $spu_with_id[$spav->spu_id];
                            if($spav->find_day==7){
                                $new_spus[$spav->spu_id]['w_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['w_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==30){
                                $new_spus[$spav->spu_id]['m_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['m_here_days']= $spav->here_days;
                            }
                            if($spav->find_day==90){
                                $new_spus[$spav->spu_id]['tm_fba_days']= $spav->fba_days;
                                $new_spus[$spav->spu_id]['tm_here_days']= $spav->here_days;
                            }
                        
                        }

                        $new_spus_b = [];
                        foreach ($spu_list_ids as $spaav) {
                            # code...
                            if(isset($new_spus[$spaav])){
                                $new_spus_b[] = $new_spus[$spaav];
                            }else{
                                $new_spus_b[] = ["spu_id"=>$spaav,"spu"=>$spu_with_id[$spaav],'w_fba_days'=>0,'w_here_days'=>0,'m_fba_days'=>0,'m_here_days'=>0,'tm_fba_days'=>0,'tm_here_days'=>0];
                            }
                        
                        }
                        $item['spu_info'] = $new_spus_b;

                    }





                }

                if(isset($ext['transfers_id'])){
                    $goods_transfers = DB::table('goods_transfers')->where('order_no',$ext['transfers_id'])->select('platform_id')->first();
                    $item['platform_name'] = '';
                    if(!empty($goods_transfers)){
                        if($goods_transfers->platform_id>0){
                            $item['platform_name'] = db::table('platform')->where('Id',$goods_transfers->platform_id)->select('name')->first()->name??'';
                        }

                    }
                }

                if(!empty($item['shop_id'])){
                    $shop_id = $item['shop_id'];
                    $shop_arr = $base->GetShop($shop_id);
                    $item['shop_name'] = $shop_arr['account'];
                    $item['country_id'] = $shop_arr['country_id'];
//                    $shop_arr = array_filter($shop, function ($t) use ($shop_id) {
//                        return $t->Id == $shop_id;
//                    });
//                    $item['country_id'] = array_column($shop_arr, 'country_id')[0];
//                    $item['shop_name'] = array_column($shop_arr, 'shop_name')[0];
                }

                $fasinCode = [];
                if (isset($item['father_asin'])){
                    foreach ($item['father_asin'] as $fasin){
                        $fasinCodeMdl = $base->GetFasinCodeNew($fasin, $item['shop_id']);
//                        if ($token == '660B08F029946C65247AC7204F1C5A72'){
//                            var_dump($fasin);
//                            var_dump($item['shop_id']);
//                            var_dump($fasinCodeMdl);
//                        }
                        if ($item['shop_id']){
                            if (!empty($fasinCodeMdl)){
                                $fasinCode[] = $fasinCodeMdl['fasin_code'] ?? '';
                            }
                        }
                    }
                    $item['fasin_code'] = $fasinCode;
                }

            }
        }
        $return['list'] = $list;
        return $return;
    }

    /**
     * 我发布的任务
     */
    public function task_released($data)
    {

        $where = "t.type=1";
        $where .= " and t.`is_deleted` = 0";
        if (!empty($data['user_id'])) {
            $where .= " and t.`user_cj`={$data['user_id']}";
        } else {
            $where .= " and t.`user_cj`=0";
        }
        //name 任务名称
        if (isset($data['name'])) {
            $where .= " and t.`name` like '%{$data['name']}%'";
        }
        //user_fz_name 负责人名称
        if (isset($data['user_fz_name'])) {
            $where .= " and u_fz.`account` like '%{$data['user_fz_name']}%'";
        }
        //class_id 任务分类
        if (isset($data['class_id'])) {
            $classArr = implode(',',$data['class_id']);
            $where .= " and t.`class_id` in ($classArr)";
        }
        //task_keys 任务关键字
        if (isset($data['task_keys'])) {
            $where .= " and t.`ext` like '%{$data['task_keys']}%'";
        }
        if (isset($data['task_id'])) {
            $where .= " and t.`Id`={$data['task_id']}";
        }
        //create_time 创建时间
        if (!empty($data['create_time'])) {
            $state_time = $data['create_time'][0] . ' 00:00:00';
            $end_time = $data['create_time'][1] . ' 23:59:59';
            $where .= " and t.create_time>='{$state_time}' and t.create_time<='{$end_time}'";
        }
        //分页
        $limit = "";
        if ((!empty($data['page'])) and (!empty($data['page_count']))) {
            $limit = " limit " . ($data['page'] - 1) * $data['page_count'] . ",{$data['page_count']}";
        }

        $sql = "select SQL_CALC_FOUND_ROWS t.*,u_fz.account as account_fz, u_cj.account as account_cj
				       from tasks t
				       inner join users u_fz on u_fz.Id = t.user_fz
				       inner join users u_cj on u_cj.Id = t.user_cj
				       where {$where}
				       order by t.create_time desc {$limit}";

        
        // echo $sql;
        $list = json_decode(json_encode(db::select($sql)), true);

        //// 总条数
        if (isset($data['page']) and isset($data['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }

        if (empty($list)) {
            $return['list'] = [];
            return $return;
        }
        $task_id = array_column($list, 'Id');

        $tasks_examine = DB::table('tasks_examine as a')
            ->leftJoin('users as b','a.user_id','=','b.Id')
            ->whereIn('task_id', $task_id)
            ->select('a.state','b.account as user_examine','a.task_id')
            ->get()
            ->toArray();

        $notExamine = [];
        $ExamineOk = [];
        $ExamineNo = [];
        foreach ($tasks_examine as $te){
            if($te->state==1||$te->state==2){
                $notExamine[$te->task_id][] = $te->user_examine;
            }elseif($te->state==3){
                $ExamineOk[$te->task_id][] = $te->user_examine;
            }elseif($te->state==4){
                $ExamineNo[$te->task_id][] = $te->user_examine;
            }
        }

        $tasks_news = DB::table('tasks_news as a')
            ->select('a.task_id', 'b.account as user_fs', 'c.account as user_js', 'a.content', 'a.create_time')
            ->leftjoin('users as b', 'b.Id', '=', 'a.user_fs')
            ->leftjoin('users as c', 'c.Id', '=', 'a.user_js')
            ->whereIn('task_id', $task_id)
            ->get();
        $tasks_news = json_decode(json_encode($tasks_news), true);
        $shop = Db::table('shop')->select('Id', 'shop_name', 'country_id')->get()->toArray();
        $plan_status = Db::table('amazon_plan_status')->get()->toArray();
        $base = new BaseModel();
        foreach ($list as &$item) {
            foreach ($tasks_news as $k => $v) {
                if ($item['Id'] == $v['task_id']) {
                    $item['tasks_news'][] = $v;
                }
            }
            $item['sku_count'] = 0;
            $item['sum'] = 0;
            $item['father_asin_info'] = [];
            if ($item['ext'] != null && $item['ext'] != '') {
                $ext = json_decode($item['ext'], true);
                $item['ext'] = $ext;
                $TaskClassModule = TaskClassModule::where('class_id', $item['class_id'])->get()->toArray();
                $item['clsss_module'] = $TaskClassModule;
                if (isset($ext['request_id'])) {
                    $detail = DB::table('amazon_buhuo_detail')->where('request_id', '=', $ext['request_id'])->select('id')->get();
                    $item['sku_count'] = count($detail);
                }
                if (isset($ext['start_time'])) {
                    $item['start_time'] = $ext['start_time'];
                }
                if (isset($ext['end_time'])) {
                    $item['end_time'] = $ext['end_time'];
                }
                if (isset($ext['request_link'])) {
                    $item['request_link'] = $ext['request_link'];
                }
                if (isset($ext['request_id'])) {
                    $item['request_id'] = $ext['request_id'];

                    $sql = "SELECT  a.request_num, a.transportation_mode_name, a.transportation_type, c.shop_id, c.transportation_date, b.fasin,c.request_status
                FROM
                    amazon_buhuo_detail a 
                LEFT JOIN self_sku b ON a.sku_id = b.id
                LEFT JOIN amazon_buhuo_request c ON a.request_id = c.id
                WHERE
                    request_id='" . $item['request_id'] . "'
                ORDER BY
                    a.custom_sku desc";
                    $data = DB::select($sql);
                    $item['shop_name'] = '';
                    $item['transport_type'] = '';
                    $item['request_status'] = '';
                    $item['transport_date'] = '';
                    $sum = 0;
                    $father_asin = [];
                    foreach ($data as $val) {
                        if ($val->fasin != '' || $val->fasin != null) {
                            $father_asin[] = $val->fasin;
                        }
                        $sum = $sum + $val->request_num;
                        $shop_arr = $base->GetShop($val->shop_id);
                        $item['shop_name'] = $shop_arr['account'];
                        $item['country_id'] = $shop_arr['country_id'];
                        $item['shop_id'] = $val->shop_id;
                       $request_status = $val->request_status;
//                        $plan_arr = array_filter($plan_status, function ($t) use ($request_status) {
//                            return $t->id == $request_status;
//                        });
                        $item['request_status'] = $base->GetPlan($request_status)['status_name'];
                        $item['transport_type'] = $val->transportation_mode_name ?? '';
                        $item['transport_date'] = date('Y-m-d', strtotime($val->transportation_date));
                    }
                    $item['father_asin'] = array_unique($father_asin);
                    $item['sum'] = $sum;
                }

                if(isset($ext['order_id'])){
                    $order = DB::table('amazon_place_order_task')->where('id', '=', $ext['order_id'])->select('order_num','shop_id','spulist','status')->first();
                    $order = json_decode(json_encode($order),true);
//                    $item['sku_count'] = $order->sku_count;
                    $item['sum'] = $order['order_num'];
                    $spu_list = explode(',',$order['spulist']);
                    foreach ($spu_list as $sk=>$sp){
                        $item['spulist'][$sk]['spu'] = $sp;
                        $thisSpuId = $base->GetSpuId($sp);
                        $item['spulist'][$sk]['one_price'] = '未知价格';
                        if(isset($spu_price[$thisSpuId])){
                            $item['spulist'][$sk]['one_price'] = $spu_price[$thisSpuId];
                        }
                    }
                    $item['task_status'] = $order['status'];
                    $shop = $base->GetShop($order['shop_id']);
                    $item['shop_name'] = $shop['account'];
                    $item['shop_id'] = $order['shop_id'];
                }

                if(isset($ext['transfers_id'])){
                    $goods_transfers = DB::table('goods_transfers')->where('order_no',$ext['transfers_id'])->select('platform_id')->first();
                    $item['platform_name'] = '';
                    if(!empty($goods_transfers)){
                        if($goods_transfers->platform_id>0){
                            $item['platform_name'] = db::table('platform')->where('Id',$goods_transfers->platform_id)->select('name')->first()->name??'';
                        }

                    }
                }

                if(!empty($item['shop_id'])){
                    $shop_id = $item['shop_id'];
                    $shop_arr = $base->GetShop($shop_id);
                    $item['shop_name'] = $shop_arr['account'];
                    $item['country_id'] = $shop_arr['country_id'];
//                    $shop_arr = array_filter($shop, function ($t) use ($shop_id) {
//                        return $t->Id == $shop_id;
//                    });
//                    $item['country_id'] = array_column($shop_arr, 'country_id')[0];
//                    $item['shop_name'] = array_column($shop_arr, 'shop_name')[0];
                }

                $fasinCode = [];
                if (isset($item['father_asin'])){
                    foreach ($item['father_asin'] as $fasin){
                        $fasinCodeMdl = $base->GetFasinCodeNew($fasin, $item['shop_id']);
//                        if ($token == '660B08F029946C65247AC7204F1C5A72'){
//                            var_dump($fasin);
//                            var_dump($item['shop_id']);
//                            var_dump($fasinCodeMdl);
//                        }
                        if ($item['shop_id']){
                            if (!empty($fasinCodeMdl)){
                                $fasinCode[] = $fasinCodeMdl['fasin_code'] ?? '';
                            }
                        }else{
                            if (!empty($fasinCodeMdl)){
                                $fasin_cdoe = array_column($fasinCodeMdl, 'fasin_code');
                                $fasinCode = array_merge($fasin_cdoe,$fasinCode);
                            }
                        }
                    }
                    $item['fasin_code'] = $fasinCode;
                }
            }
        }

        $return['list'] = $list;
        return $return;
    }

    /*
     * 删除任务
     * @param Id 任务id
     */
    public function task_del($data)
    {
        // 删除任务信息、任务审核、任务节点、节点任务、任务消息、站内消息
        $task = DB::table('tasks')->where('Id', $data['Id'])->select('class_id', 'ext')->first();
        if (!empty($task)) {
            $ext = json_decode($task->ext, true);

            if (in_array($task->class_id, [3,4,124, 127])) {
                $id = $ext['request_id'];
                $goods = DB::table('goods_transfers')->where('order_no', '=', $id)->select('is_push')->first();
                if($goods->is_push==4){
                    return $this->back('订单已开始流转，无法取消', '500');
                }
                $res = DB::table('amazon_buhuo_request')->where('id', '=', $id)->update(['request_status' => 1]);

                $goods = DB::table('goods_transfers')->where('order_no', '=', $id)->update(['is_push' => -1,'status'=>-1]);
//                if (!$res) {
//                    return '删除失败';
//                }
            }
            if($task->class_id == 2){
                return '云仓任务无法直接删除，请尝试在补货计划表撤销';
            }
            if ($task->class_id == 19) {
                $id = $ext['order_id'];
                $res = DB::table('amazon_place_order_task')->where('id', '=', $id)->update(['status' => -1]);
            }
        }
//        $sql = "delete t, te, tn, n, ts, ti
//					from tasks t
//					left join tasks_examine te on te.task_id = t.Id
//					left join tasks_news tn on tn.task_id = t.Id
//					left join tasks_node n on n.task_id = t.Id
//					left join tasks_son ts on ts.task_id = t.Id
//					left join tidings ti on ti.object_type=1 and ti.object_id=t.Id
//					where t.`Id`={$data['Id']}";
//        $del = db::delete($sql);
        $del = $this->taskModel::query()->where('Id', $data['Id'])->update(['is_deleted' => 1]);
        if ($del) {
            return 1;
        } else {
            return '删除失败';
        }
    }

    /**
     * 任务审核
     * @parma Id 任务审核id
     * @param task_id 任务id
     * @param desc 审核描述
     * @param state 状态：1.待审核、2.已同意、3.已拒绝
     * @logic 修改审核（是否可审核、审核状态） --> 获取下个审核信息 --> 有：修改审核（是否可审核），发送站内消息给审核人；无修改任务（任务状态），触发任务
     */
    public function tasks_examine($data)
    {
        try {
            // 任务信息
            $task_find = DB::table('tasks as a')->leftJoin('task_class as b','a.class_id','=','b.id')->where('a.Id',$data['task_id'])->select('a.*','b.notice')->get();
            $task_find = json_decode(json_encode($task_find), true);
            if (empty($task_find)) {
                return '任务不存在';
            }
            $task_id = $task_find[0]['Id'];
            if ($task_find[0]['audit_method'] === 1 || $task_find[0]['audit_method'] === 3) {
                $where = "`Id` ={$data['Id']}";
            } else {
                $where = "`task_id` = {$task_id}";
            }
            if (!empty($task_find[0]['ext'])) {
                $ext = json_decode($task_find[0]['ext'], true);
                $task = $task_find[0];
            }
            db::beginTransaction();    //开启事务

            //当前时间
            $time = time();
            $time_now = date('Y-m-d H:i:s', $time);

            if ($task_find[0]['audit_method'] != 4){
                //// 修改审核（是否可审核、审核状态）
                $set = "state={$data['state']}, time_sh='{$time_now}'";
                if ($data['state'] != 2) $set .= ",is_examine=1";

                //desc 审核描述
                if (!empty($data['desc'])) {
                    $set .= ", `desc`='{$data['desc']}'";
                }
                if (!empty($data['img'])) {
                    $img = json_encode($data['img']);
                    $set .= ", `img`='{$img}'";
                }
                if (!empty($data['file'])) {
                    $file = json_encode($data['file']);
                    $set .= ", `file`='{$file}'";
                }
                $sql = "update tasks_examine
					set {$set}
					where {$where}";//`Id` = {$data['Id']}
                $examine_update = db::update($sql);
                if (!$examine_update) {
                    db::rollback();// 回调
                    return '修改审核失败--tasks_examine表';
                }
            }

            //审核
            if ($data['state'] == 4) {
                //拒绝

                //修改任务状态

                $sql = "update tasks
						set state=2, time_examine='{$time_now}'
						where `Id` = {$task_id}";
                $task_update = db::update($sql);
                if (in_array($task_find[0]['class_id'], [2, 3, 4, 124, 127])){
                    if (isset($ext['request_id'])) {
                        $update_request = Db::table('amazon_buhuo_request')->where('id', $ext['request_id'])->update(['request_status' => 1]);
                        if (!$update_request) {
                            db::rollback();// 回调
                            return '修改任务状态失败--amazon_buhuo_request表';
                        }
                        $goods = DB::table('goods_transfers')->where('order_no', '=', $ext['request_id'])->update(['is_push' => -1,'status'=>1]);
                        if(!$goods){
                            db::rollback();// 回调
                            return $this->back('取消失败-goods_transfers表', '500');
                        }
                        $box = DB::table('goods_transfers_box')->where('order_no',$ext['request_id'])->select('id')->first();
                        if(!empty($box)){
                            $box_data = DB::table('goods_transfers_box_detail')->where('box_id',$box->id)->select('custom_sku_id','box_num','location_ids','shelf_num')->get();
                            foreach ($box_data as $bb){
                                if($bb->shelf_num>0){
                                    db::rollback();// 回调
                                    return $this->back('订单已开始流转，无法拒绝', '500');
                                }
                            }
                            DB::table('goods_transfers_box')->where('id',$box->id)->update(['is_delete'=>1]);
                        }else{
                            db::rollback();// 回调
                            return $this->back('取消失败，没有查到出库任务箱号', '500');
                        }
                        if($task_find[0]['class_id']==2){
                            //如果是云仓计划则加入取消订单队列
                            $params['order_no'] = $ext['request_id'];
                            $params['order_type'] = 'B2BRK';
                            $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                            try {
                                $cloud::cancelJob($params);
                            } catch(\Exception $e){
                                Redis::Lpush('order_cancel_fail',json_encode($params));
                            }
                        }
                    }
                }

//                if (in_array($task_find[0]['class_id'], [127])) {
//                    if (isset($ext['request_id'])) {
//                        $update_request = Db::table('amazon_buhuo_request')->where('id', $ext['request_id'])->update(['request_status' => 1]);
//                        if (!$update_request) {
//                            db::rollback();// 回调
//                            return '修改任务状态失败--amazon_buhuo_request表';
//                        }
//                    }else{
//                        db::rollback();// 回调
//                        return '未给定补货计划标识！';
//                    }
//                }

                if (isset($ext['order_id'])) {
                    $update_order = Db::table('amazon_place_order_task')->where('id', $ext['order_id'])->update(['status' => -1]);
                }

                if ($task['class_id'] == 23){
                    if (isset($ext['contract_no'])){
                        $contractMdl = DB::table('cloudhouse_contract_total')->where('contract_no', $ext['contract_no'])->first();
                        if (empty($contractMdl)){
                            db::rollback();// 回调
                            return '修改任务状态失败--未查询到该合同数据！';
                        }
                        // 被拒绝状态-2
                        $contract = DB::table('cloudhouse_contract_total')->where('contract_no', $ext['contract_no'])->update(['contract_status' => -2]);
                        if (!$contract){
                            db::rollback();// 回调
                            return '修改任务状态失败--cloudhouse_contract_total表状态修改失败';
                        }
                    }else{
                        db::rollback();// 回调
                        return '修改任务状态失败--任务详情未给定合同号';
                    }

//                    $planIds = explode(',', $contractMdl->bind_place_ids);
//                    foreach ($planIds as $id){
//                        $order = DB::table('amazon_place_order_task')->where('id', $id)->update(['status' => 3]);
//                        if (!$order){
//                            db::rollback();// 回调
//                            return '修改任务状态失败--amazon_place_order_task表状态修改失败';
//                        }
//                    }
                }

                //出入库任务
                if(isset($ext['transfers_id'])){
                    $transfers = Db::table('goods_transfers')->where('order_no', $ext['transfers_id'])->select('id','status')->first();
                    if(!empty($transfers)){
                        Db::table('goods_transfers')->where('id', $transfers->id)->update(['status'=>1,'is_push' => -1]);
                    }else{
                        db::rollback();// 回调

                        return '没有此任务内容，无需审核';
                    }
                }

                // 票据
                if (in_array($task['class_id'], [26, 69, 70])){
                    if(isset($ext['bill_id'])){
                        $billMdl = Db::table('financial_bill')->where('id', $ext['bill_id'])->first();
                        if(!empty($billMdl)){
                            Db::table('financial_bill')->where('id', $billMdl->id)->update(['status'=>-2, 'updated_at' => date('Y-m-d H:i:s')]);
                        }else{
                            db::rollback();// 回调
                            return '没有此任务内容，无需审核';
                        }
                    }else{
                        db::rollback();// 回调
                        return '任务详情未给定票据标识！';
                    }
                }

                if (!$task_update) {
                    db::rollback();// 回调
                    return '修改任务状态失败--tasks表';
                }

                //发送站内消息给负责人
                $content = "任务：{$task_find[0]['name']}，审核被拒绝";
            } else if ($data['state'] == 2) {
                if (isset($data['user_id'])) {
                    $sql = "update tasks_examine
						set state=2
						where `Id` ={$data['Id']} and user_id={$data['user_id']}";
                    $tasks_examine_update = db::update($sql);
                }
            } else {
                //同意

                //// 获取下个审核信息

                //审核方式为全部成员审核通过
                if ($task_find[0]['audit_method'] === 1) {

                    $dtask_id = $data['task_id'];

                    $sql = "select Id
						from tasks_examine
						where 
						`task_id`={$dtask_id} and `is_examine`=2";

                    $examine_next = json_decode(json_encode(db::select($sql)), true);


                    //有：修改审核（是否可审核），发送站内消息给审核人；
                    //无:修改任务（任务状态），触发任务
                    if (count($examine_next) == 0) {

                        //有：修改审核（是否可审核），发送站内消息给审核人；
                        //无:修改任务（任务状态），触发任务
                        //修改任务状态
                        $sql = "update tasks
							set state=3, time_examine='{$time_now}'
							where `Id` ={$data['task_id']}";
                        $task_update = db::update($sql);
                        if (!$task_update) {
                            db::rollback();// 回调
                            return '修改任务状态失败--tasks表';
                        }
                        if (in_array($task_find[0]['class_id'], [127])){
                            if (isset($ext['request_id'])) {
                                $update_request = Db::table('amazon_buhuo_request')->where('id', $ext['request_id'])->update(['request_status' => 4]);
                                if (!$update_request) {
                                    db::rollback();// 回调
                                    return '修改任务状态失败--amazon_buhuo_request表';
                                }
//                                //发送站内消息给负责人
//                                $content = "任务：{$task_find[0]['name']}，审核已通过";
//                                //触发任务
//                                $arr = array();
//                                $arr['task_id'] = $data['task_id'];
//                                $task_trigger = $this->task_trigger($arr);
//                                if ($task_trigger != 1) {
//                                    return $task_trigger;
//                                }
                            }else{
                                db::rollback();// 回调
                                return '未给定补货计划标识！';
                            }
                        }

                        if (in_array($task_find[0]['class_id'], [2,3,4,124])){
                            if (isset($ext['request_id'])) {
                                $content = "任务：{$task_find[0]['name']}，审核已通过";

                                //工厂直发仓   需要扣除箱规对应的库存
                                if($task_find[0]['class_id']==124){
                                   $abdetail = db::table('amazon_buhuo_detail')->where('request_id',$ext['request_id'])->get();
                                    foreach ($abdetail as $abdv) {
                                        # code...
                                        $abdi['supplier_id'] = $abdv->supplier_id;
                                        $abdi['custom_sku_id'] = $abdv->custom_sku_id;
                                        $abdi['custom_sku'] = $abdv->custom_sku;
                                        $abdi['num'] = $abdv->request_num;
                                        $abdi['task_id'] =  $dtask_id;
                                        db::table('amazon_buhuo_report_num')->insert($abdi);
                                    }
                                }
                                
                                $request_status = Db::table('amazon_buhuo_request')->where('id', $ext['request_id'])->select('request_status')->first();
                                $update_goods = Db::table('goods_transfers')->where('order_no', $ext['request_id'])->update(['status' => 3,'push_time'=>date('Y-m-d H:i:s')]);
                                if ($request_status->request_status == 3) {
                                    if ($task_find[0]['class_id'] == 124){
                                        $status = 6;
                                    }else{
                                        $status = 4;
                                    }
                                    $update_request = Db::table('amazon_buhuo_request')->where('id', $ext['request_id'])->update(['request_status' => $status]);
                                    if (!$update_request) {
                                        db::rollback();// 回调
                                        return '修改任务状态失败--amazon_buhuo_request表';
                                    }
                                    //云仓补货计划则加入出库单队列
                                    if($task_find[0]['class_id']==2) {
                                        //                                    $params['method'] = 'stockout.create';
                                        $params['order_no'] = $ext['request_id'];
                                        $params['type'] = 'B2BCK';
                                        $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                                        try {
                                            $cloud::outhouseJob($params);
                                            Redis::Lpush('cloud_outRequest',$ext['request_id']);
                                        } catch(\Exception $e){
                                            Redis::Lpush('out_house_fail',$ext['request_id']);
                                        }
                                    }
//                                    //发送站内消息给负责人
//                                    $content = "任务：{$task_find[0]['name']}，审核已通过";
//                                    //触发任务
//                                    $arr = array();
//                                    $arr['task_id'] = $data['task_id'];
//                                    $task_trigger = $this->task_trigger($arr);
//                                    if ($task_trigger != 1) {
//                                        return $task_trigger;
//                                    }
                                }else{
                                    db::rollback();// 回调
                                    return '补货计划id:'.$ext['request_id'].'状态不为已发布，待审核！';
                                }
                            }
                        }

                        if(isset($ext['order_id'])){
                            $orderData = Db::table('amazon_place_order_task')->where('id', $ext['order_id'])->select('one_cate_id')->first();
                            if(!empty($orderData)){
                                if($orderData->one_cate_id!=432){
                                    $day = date("l");
//                                 if($day!='Monday'&&$day!='Tuesday'){
//                                     db::rollback();// 回调
//                                     return '非审核日！请周一周二再审核下单任务';
//                                 }
                                }
                                $update_order = Db::table('amazon_place_order_task')->where('id', $ext['order_id'])->update(['status' => 2]);
                                if (!$update_order) {
                                    db::rollback();// 回调
                                    return '修改任务状态失败--amazon_place_order_task';
                                }
                            }
                        }

                        // 下单合同审核任务
                        if (isset($ext['contract_no'])){
                            // 审核任务
                            if ($task['class_id'] == 23){
                                $contractMdl = DB::table('cloudhouse_contract_total')->where('contract_no', $ext['contract_no'])->first();
                                if (empty($contractMdl)){
                                    db::rollback();// 回调
                                    return '修改任务状态失败--未查询到该合同数据！';
                                }
                                $contract = DB::table('cloudhouse_contract_total')->where('contract_no', $ext['contract_no'])->update(['contract_status' => 2, 'purend_date' => microtime(true)]);
                                if (!$contract){
                                    db::rollback();// 回调
                                    return '修改任务状态失败--cloudhouse_contract_total表状态修改失败';
                                }
                                $cloudhouse = new \App\Models\CloudHouse();
                                $to = $cloudhouse->ConcactToOneDog(['contract_no'=>$contractMdl->contract_no]);
                                $planIds = explode(',', $contractMdl->bind_place_ids);
                                foreach ($planIds as $id){
                                    $orderDetail = DB::table('amazon_place_order_detail')->where('order_id', $id)->get();
                                    $is_update = 1;
                                    // 判断如果存在为开合同的商品则不更改下单计划状态
                                    foreach ($orderDetail as $od){
                                        if ($od->is_contracted == 0){
                                            $is_update = 0;
                                            break;
                                        }
                                    }
                                    if ($is_update){
                                        $order = DB::table('amazon_place_order_task')->where('id', $id)->update(['status' => 4]);
//                                        if (!$order){
//                                            db::rollback();// 回调
//                                            return '修改任务状态失败--amazon_place_order_task表状态修改失败';
//                                        }
                                    }
                                }
                            }
                            // 反审核任务
                            if ($task['class_id'] == 78){
                                $contractMdl = DB::table('cloudhouse_contract_total')->where('contract_no', $ext['contract_no'])->first();
                                if (empty($contractMdl)){
                                    db::rollback();// 回调
                                    return '修改任务状态失败--未查询到该合同数据！';
                                }
                                $contract = DB::table('cloudhouse_contract_total')->where('id', $contractMdl->id)->update(['contract_status' => -1]);
                                $cloudhouse = new \App\Models\CloudHouse();
                                $to = $cloudhouse->ConcactToOneDog(['contract_no'=>$contractMdl->contract_no]);
                                $placIds = explode(',', $contractMdl->bind_place_ids);
                                foreach ($placIds as $id){
                                    $placeOrder = DB::table('amazon_place_order_task')->where('id', $id)->update(['status' => 3]);
                                }
                                $task = DB::table('tasks')->where('ext', 'like', '%contract_no='.$contractMdl->contract_no.'%')->update(['is_deleted' => 1]);
                                if (!$contract){
                                    db::rollback();// 回调
                                    return '修改任务状态失败--cloudhouse_contract_total表状态修改失败';
                                }
                            }
                        }

                        //出入库任务
                        if(isset($ext['transfers_id'])){
                            $transfers = Db::table('goods_transfers')->where('order_no', $ext['transfers_id'])->select('id','status')->first();
                            if(!empty($transfers)){
                                if($transfers->status==2){
                                    Db::table('goods_transfers')->where('id', $transfers->id)->update(['status'=>3]);
                                }
                            }else{
                                db::rollback();// 回调
                                return '没有此任务内容，无需审核';
                            }
                        }

                        // 票据
                        if(isset($ext['bill_id'])){
                            $billMdl = Db::table('financial_bill')->where('id', $ext['bill_id'])->first();
                            if(!empty($billMdl)){
                                Db::table('financial_bill')->where('id', $billMdl->id)->update(['status' => 2, 'updated_at' => date('Y-m-d H:i:s')]);
                            }else{
                                db::rollback();// 回调
                                return '没有此任务内容，无需审核';
                            }
                        }

                        //平台间库存调拔审核
                        if (isset($ext['adjust_id']) && in_array($task['class_id'], [32, 33])) {

                            $adjustInfo = DB::table('adjust_inventory_platform')->where('id', $ext['adjust_id'])->first();
                            if (!$adjustInfo) {
                                db::rollback();
                                return '没有此任务内容，无需审核';
                            }

                            $res = (new InventoryModel())->adjustInventory([
                                'warehouse_id'        => $adjustInfo->warehouse_id,
                                'platform_id'         => $adjustInfo->platform_id,
                                'receive_platform_id' => $adjustInfo->receive_platform_id,
                                'user_id'             => $adjustInfo->user_id,
                                'sku_data'            => json_decode($adjustInfo->ext, true),
                            ]);

                            if ($res['code'] == 500) {
                                db::rollback();
                                return $res['msg'];
                            }
                        }


                        //发送站内消息给负责人
                        $content = "任务：{$task_find[0]['name']}，审核已通过";
                        //触发任务
                        $arr = array();
                        $arr['task_id'] = $data['task_id'];
                        $task_trigger = $this->task_trigger($arr);
                        if ($task_trigger != 1) {
                            return $task_trigger;
                        }
                    }

                } else if ($task_find[0]['audit_method'] === 2) {

                    //审核方式为单人审核通过
                    $sql = "update tasks
						set state=3, time_examine='{$time_now}'
						where `Id` = {$task_id}";
                    $task_update = db::update($sql);
                    if (!empty($task_find[0]['ext'])) {
                        $ext = json_decode($task_find[0]['ext'], true);
                        if (in_array($task_find[0]['class_id'], [127])){
                            if (isset($ext['request_id'])) {
                                $update_request = Db::table('amazon_buhuo_request')->where('id', $ext['request_id'])->update(['request_status' => 4]);
                                if (!$update_request) {
                                    db::rollback();// 回调
                                    return '修改任务状态失败--amazon_buhuo_request表';
                                }
//                                //发送站内消息给负责人
//                                $content = "任务：{$task_find[0]['name']}，审核已通过";
//                                //触发任务
//                                $arr = array();
//                                $arr['task_id'] = $data['task_id'];
//                                $task_trigger = $this->task_trigger($arr);
//                                if ($task_trigger != 1) {
//                                    return $task_trigger;
//                                }
                            }else{
                                db::rollback();// 回调
                                return '未给定补货计划标识！';
                            }
                        }

                        if (in_array($task_find[0]['class_id'], [2,3,4,124])){
                            if (isset($ext['request_id'])) {
                                $content = "任务：{$task_find[0]['name']}，审核已通过";
                                $request_status = Db::table('amazon_buhuo_request')->where('id', $ext['request_id'])->select('request_status')->first();
                                $update_goods = Db::table('goods_transfers')->where('order_no', $ext['request_id'])->update(['status' => 3,'push_time'=>date('Y-m-d H:i:s')]);
                                if ($request_status->request_status == 3) {
                                    if ($task_find[0]['class_id'] == 124){
                                        $status = 6;
                                    }else{
                                        $status = 4;
                                    }
                                    $update_request = Db::table('amazon_buhuo_request')->where('id', $ext['request_id'])->update(['request_status' => $status]);
                                    if (!$update_request) {
                                        db::rollback();// 回调
                                        return '修改任务状态失败--amazon_buhuo_request表';
                                    }
                                    //云仓补货计划则加入出库单队列
                                    if($task_find[0]['class_id']==2) {
                                        //                                    $params['method'] = 'stockout.create';
                                        $params['order_no'] = $ext['request_id'];
                                        $params['type'] = 'B2BCK';
                                        $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                                        try {
                                            $cloud::outhouseJob($params);
                                            Redis::Lpush('cloud_outRequest',$ext['request_id']);
                                        } catch(\Exception $e){
                                            Redis::Lpush('out_house_fail',$ext['request_id']);
                                        }
                                    }
//                                    //发送站内消息给负责人
//                                    $content = "任务：{$task_find[0]['name']}，审核已通过";
//                                    //触发任务
//                                    $arr = array();
//                                    $arr['task_id'] = $data['task_id'];
//                                    $task_trigger = $this->task_trigger($arr);
//                                    if ($task_trigger != 1) {
//                                        return $task_trigger;
//                                    }
                                }else{
                                    db::rollback();// 回调
                                    return '补货计划id:'.$ext['request_id'].'状态不为已发布，待审核！';
                                }
                            }
                        }

                        if(isset($ext['order_id'])){
                            $orderData = Db::table('amazon_place_order_task')->where('id', $ext['order_id'])->select('one_cate_id')->first();
                            if(!empty($orderData)){
                                if($orderData->one_cate_id!=432){
                                    $day = date("l");
//                                 if($day!='Monday'&&$day!='Tuesday'){
//                                     db::rollback();// 回调
//                                     return '非审核日！请周一周二再审核下单任务';
//                                 }
                                }
                                $update_order = Db::table('amazon_place_order_task')->where('id', $ext['order_id'])->update(['status' => 2]);
                                if (!$update_order) {
                                    db::rollback();// 回调
                                    return '修改任务状态失败--amazon_buhuo_request表';
                                }
                            }
                        }
                        // 下单合同审核任务
                        if (isset($ext['contract_no'])){
                            // 审核任务
                            if ($task['class_id'] == 23){
                                $contractMdl = DB::table('cloudhouse_contract_total')->where('contract_no', $ext['contract_no'])->first();
                                if (empty($contractMdl)){
                                    db::rollback();// 回调
                                    return '修改任务状态失败--未查询到该合同数据！';
                                }
                                $contract = DB::table('cloudhouse_contract_total')->where('contract_no', $ext['contract_no'])->update(['contract_status' => 2, 'purend_date' => microtime(true)]);
                                if (!$contract){
                                    db::rollback();// 回调
                                    return '修改任务状态失败--cloudhouse_contract_total表状态修改失败';
                                }
                                $planIds = explode(',', $contractMdl->bind_place_ids);
                                foreach ($planIds as $id){
                                    $orderDetail = DB::table('amazon_place_order_detail')->where('order_id', $id)->get();
                                    $is_update = 1;
                                    // 判断如果存在为开合同的商品则不更改下单计划状态
                                    foreach ($orderDetail as $od){
                                        if ($od->is_contracted == 0){
                                            $is_update = 0;
                                            break;
                                        }
                                    }
                                    if ($is_update){
                                        $order = DB::table('amazon_place_order_task')->where('id', $id)->update(['status' => 4]);
                                        if (!$order){
                                            db::rollback();// 回调
                                            return '修改任务状态失败--amazon_place_order_task表状态修改失败';
                                        }
                                    }
                                }
                            }
                            // 反审核任务
                            if ($task['class_id'] == 78){
                                $contractMdl = DB::table('cloudhouse_contract_total')->where('contract_no', $ext['contract_no'])->first();
                                if (empty($contractMdl)){
                                    db::rollback();// 回调
                                    return '修改任务状态失败--未查询到该合同数据！';
                                }
                                $contract = DB::table('cloudhouse_contract_total')->where('id', $contractMdl->id)->update(['contract_status' => -1]);
                                $placIds = explode(',', $contractMdl->bind_place_ids);
                                foreach ($placIds as $id){
                                    $placeOrder = DB::table('amazon_place_order_task')->where('id', $id)->update(['status' => 3]);
                                }
                                $task = DB::table('tasks')->where('ext', 'like', '%contract_no='.$contractMdl->contract_no.'%')->update(['is_deleted' => 1]);
                                if (!$contract){
                                    db::rollback();// 回调
                                    return '修改任务状态失败--cloudhouse_contract_total表状态修改失败';
                                }
                            }
                        }

                        //出入库任务
                        if(isset($ext['transfers_id'])){
                            $transfers = Db::table('goods_transfers')->where('order_no', $ext['transfers_id'])->select('id','status')->first();
                            if(!empty($transfers)){
                                if($transfers->status==2){
                                    Db::table('goods_transfers')->where('id', $transfers->id)->update(['status'=>3]);
                                }
                            }else{
                                db::rollback();// 回调
                                return '没有此任务内容，无需审核';
                            }
                        }

                        // 票据
                        if(isset($ext['bill_id'])){
                            $billMdl = Db::table('financial_bill')->where('id', $ext['bill_id'])->first();
                            if(!empty($billMdl)){
                                Db::table('financial_bill')->where('id', $billMdl->id)->update(['status' => 2, 'updated_at' => date('Y-m-d H:i:s')]);
                            }else{
                                db::rollback();// 回调
                                return '没有此任务内容，无需审核';
                            }
                        }

                        //平台间库存调拔审核
                        if (isset($ext['adjust_id']) && in_array($task['class_id'], [32, 33])) {

                            $adjustInfo = DB::table('adjust_inventory_platform')->where('id', $ext['adjust_id'])->first();
                            if (!$adjustInfo) {
                                db::rollback();
                                return '没有此任务内容，无需审核';
                            }

                            $res = (new InventoryModel())->adjustInventory([
                                'warehouse_id'        => $adjustInfo->warehouse_id,
                                'platform_id'         => $adjustInfo->platform_id,
                                'receive_platform_id' => $adjustInfo->receive_platform_id,
                                'user_id'             => $adjustInfo->user_id,
                                'sku_data'            => json_decode($adjustInfo->ext, true),
                            ]);

                            if ($res['code'] == 500) {
                                db::rollback();
                                return $res['msg'];
                            }
                        }
                    }
                    if (!$task_update) {
                        db::rollback();// 回调
                        return '修改任务状态失败--tasks表';
                    }
                    //发送站内消息给负责人
                    $content = "任务：{$task_find[0]['name']}，审核已通过";
                    //触发任务
                    $arr = array();
                    $arr['task_id'] = $data['task_id'];
                    $task_trigger = $this->task_trigger($arr);
                    if ($task_trigger != 1) {
                        return $task_trigger;
                    }
                } else if ($task_find[0]['audit_method'] === 3) {
                    //审核方式为总经理审核通过
                    $sql = "select Id
						from tasks_examine
						where 
						task_id={$data['task_id']} and `is_examine`=2";
                    $examine_next = json_decode(json_encode(db::select($sql)), true);
                    if (count($examine_next) == 0) {
                        //有：修改审核（是否可审核），发送站内消息给审核人；
                        //无:修改任务（任务状态），触发任务
                        //修改任务状态
                        $sql = "update tasks
							set state=3, time_examine='{$time_now}'
							where `Id` ={$data['task_id']}";
                        $task_update = db::update($sql);
                        if (!$task_update) {
                            db::rollback();// 回调
                            return '修改任务状态失败--tasks表';
                        }
                    }
                    $sql2 = "select user_id
						from tasks_examine
						where 
						`Id` = {$data['Id']}";
                    $audit = db::select($sql2);
                    $user_id = 0;
                    if (!empty($audit)) $user_id = $audit[0]->user_id;
                    if ($user_id!=0) {
                        if (!empty($task_find[0]['ext'])) {
                            $ext = json_decode($task_find[0]['ext'], true);
//                            if($user_id==14){
                                if (in_array($task_find[0]['class_id'], [127])){
                                    if (isset($ext['request_id'])) {
                                        $update_request = Db::table('amazon_buhuo_request')->where('id', $ext['request_id'])->update(['request_status' => 4]);
                                        if (!$update_request) {
                                            db::rollback();// 回调
                                            return '修改任务状态失败--amazon_buhuo_request表';
                                        }
                                        //发送站内消息给负责人
                                        $content = "任务：{$task_find[0]['name']}，审核已通过";
                                        //触发任务
                                        $arr = array();
                                        $arr['task_id'] = $data['task_id'];
                                        $task_trigger = $this->task_trigger($arr);
                                        if ($task_trigger != 1) {
                                            return $task_trigger;
                                        }
                                    }else{
                                        db::rollback();// 回调
                                        return '未给定补货计划标识！';
                                    }
                                }
                                if (in_array($task_find[0]['class_id'], [2,3,4,124])){
                                    if (isset($ext['request_id'])) {
                                        $content = "任务：{$task_find[0]['name']}，审核已通过";
                                        $request_status = Db::table('amazon_buhuo_request')->where('id', $ext['request_id'])->select('request_status')->first();
                                        $update_goods = Db::table('goods_transfers')->where('order_no', $ext['request_id'])->update(['status' => 3,'push_time'=>date('Y-m-d H:i:s')]);
                                        if ($request_status->request_status == 3) {
                                            if ($task_find[0]['class_id'] == 124){
                                                $status = 6;
                                            }else{
                                                $status = 4;
                                            }
                                            $update_request = Db::table('amazon_buhuo_request')->where('id', $ext['request_id'])->update(['request_status' => $status]);
                                            if (!$update_request) {
                                                db::rollback();// 回调
                                                return '修改任务状态失败--amazon_buhuo_request表';
                                            }
                                            //云仓补货计划则加入出库单队列
                                            if($task_find[0]['class_id']==2) {
                                                //                                    $params['method'] = 'stockout.create';
                                                $params['order_no'] = $ext['request_id'];
                                                $params['type'] = 'B2BCK';
                                                $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                                                try {
                                                    $cloud::outhouseJob($params);
                                                    Redis::Lpush('cloud_outRequest',$ext['request_id']);
                                                } catch(\Exception $e){
                                                    Redis::Lpush('out_house_fail',$ext['request_id']);
                                                }
                                            }
                                            //发送站内消息给负责人
                                            $content = "任务：{$task_find[0]['name']}，审核已通过";
                                            //触发任务
                                            $arr = array();
                                            $arr['task_id'] = $data['task_id'];
                                            $task_trigger = $this->task_trigger($arr);
                                            if ($task_trigger != 1) {
                                                return $task_trigger;
                                            }
                                        }else{
                                            db::rollback();// 回调
                                            return '补货计划id:'.$ext['request_id'].'状态不为已发布，待审核！';
                                        }
                                    }
                                }
                                if (isset($ext['order_id'])) {
                                    $orderData = Db::table('amazon_place_order_task')->where('id', $ext['order_id'])->select('one_cate_id')->first();
                                    if(!empty($orderData)){
                                        if($orderData->one_cate_id!=432){
                                            $day = date("l");
                                        }
                                        $update_order = Db::table('amazon_place_order_task')->where('id', $ext['order_id'])->update(['status' => 2]);
                                        if (!$update_order) {
                                            db::rollback();// 回调
                                            return '修改任务状态失败--amazon_buhuo_request表';
                                        }
                                        //发送站内消息给负责人
                                        $content = "任务：{$task_find[0]['name']}，审核已通过";
                                        //触发任务
                                        $arr = array();
                                        $arr['task_id'] = $data['task_id'];
                                        $task_trigger = $this->task_trigger($arr);
                                        if ($task_trigger != 1) {
                                            return $task_trigger;
                                        }
                                    }

                                }
                                // 下单合同审核任务
                                if (isset($ext['contract_no'])) {
                                    // 审核任务
                                    if ($task['class_id'] == 23){
                                        $contractMdl = DB::table('cloudhouse_contract_total')->where('contract_no', $ext['contract_no'])->first();
                                        if (empty($contractMdl)){
                                            db::rollback();// 回调
                                            return '修改任务状态失败--未查询到该合同数据！';
                                        }
                                        $contract = DB::table('cloudhouse_contract_total')->where('contract_no', $ext['contract_no'])->update(['contract_status' => 2, 'purend_date' => microtime(true)]);
                                        if (!$contract){
                                            db::rollback();// 回调
                                            return '修改任务状态失败--cloudhouse_contract_total表状态修改失败';
                                        }
                                        $planIds = explode(',', $contractMdl->bind_place_ids);
                                        foreach ($planIds as $id){
                                            $orderDetail = DB::table('amazon_place_order_detail')->where('order_id', $id)->get();
                                            $is_update = 1;
                                            // 判断如果存在为开合同的商品则不更改下单计划状态
                                            foreach ($orderDetail as $od){
                                                if ($od->is_contracted == 0){
                                                    $is_update = 0;
                                                    break;
                                                }
                                            }
                                            if ($is_update){
                                                $order = DB::table('amazon_place_order_task')->where('id', $id)->update(['status' => 4]);
                                                if (!$order){
                                                    db::rollback();// 回调
                                                    return '修改任务状态失败--amazon_place_order_task表状态修改失败';
                                                }
                                            }
                                        }
                                        //发送站内消息给负责人
                                        $content = "任务：{$task_find[0]['name']}，审核已通过";
                                        //触发任务
                                        $arr = array();
                                        $arr['task_id'] = $data['task_id'];
                                        $task_trigger = $this->task_trigger($arr);
                                        if ($task_trigger != 1) {
                                            return $task_trigger;
                                        }
                                    }
                                    // 反审核任务
                                    if ($task['class_id'] == 78){
                                        $contractMdl = DB::table('cloudhouse_contract_total')->where('contract_no', $ext['contract_no'])->first();
                                        if (empty($contractMdl)){
                                            db::rollback();// 回调
                                            return '修改任务状态失败--未查询到该合同数据！';
                                        }
                                        $contract = DB::table('cloudhouse_contract_total')->where('id', $contractMdl->id)->update(['contract_status' => -1]);
                                        $placIds = explode(',', $contractMdl->bind_place_ids);
                                        foreach ($placIds as $id){
                                            $placeOrder = DB::table('amazon_place_order_task')->where('id', $id)->update(['status' => 3]);
                                        }
                                        $task = DB::table('tasks')->where('ext', 'like', '%contract_no='.$contractMdl->contract_no.'%')->update(['is_deleted' => 1]);
                                        if (!$contract){
                                            db::rollback();// 回调
                                            return '修改任务状态失败--cloudhouse_contract_total表状态修改失败';
                                        }
                                        //发送站内消息给负责人
                                        $content = "任务：{$task_find[0]['name']}，审核已通过";
                                        //触发任务
                                        $arr = array();
                                        $arr['task_id'] = $data['task_id'];
                                        $task_trigger = $this->task_trigger($arr);
                                        if ($task_trigger != 1) {
                                            return $task_trigger;
                                        }
                                    }
                                }
                                // 票据
                                if(isset($ext['bill_id'])){
                                    $billMdl = Db::table('financial_bill')->where('id', $ext['bill_id'])->first();
                                    if(!empty($billMdl)){
                                        Db::table('financial_bill')->where('id', $billMdl->id)->update(['status' => 2, 'updated_at' => date('Y-m-d H:i:s')]);
                                    }else{
                                        db::rollback();// 回调
                                        return '没有此任务内容，无需审核';
                                    }
                                    //发送站内消息给负责人
                                    $content = "任务：{$task_find[0]['name']}，审核已通过";
                                    //触发任务
                                    $arr = array();
                                    $arr['task_id'] = $data['task_id'];
                                    $task_trigger = $this->task_trigger($arr);
                                    if ($task_trigger != 1) {
                                        return $task_trigger;
                                    }
                                }

                                //出入库任务
                                if(isset($ext['transfers_id'])){
                                    $transfers = Db::table('goods_transfers')->where('order_no', $ext['transfers_id'])->select('id','status')->first();
                                    if(!empty($transfers)){
                                        if($transfers->status==2){
                                            Db::table('goods_transfers')->where('id', $transfers->id)->update(['status'=>3]);
                                        }
                                    }else{
                                        db::rollback();// 回调
                                        return '没有此任务内容，无需审核';
                                    }
                                    //发送站内消息给负责人
                                    $content = "任务：{$task_find[0]['name']}，审核已通过";
                                    //触发任务
                                    $arr = array();
                                    $arr['task_id'] = $data['task_id'];
                                    $task_trigger = $this->task_trigger($arr);
                                    if ($task_trigger != 1) {
                                        return $task_trigger;
                                    }
                                }

                                //平台间库存调拔审核
                                if (isset($ext['adjust_id']) && in_array($task['class_id'], [32, 33])) {

                                    $adjustInfo = DB::table('adjust_inventory_platform')->where('id', $ext['adjust_id'])->first();
                                    if (!$adjustInfo) {
                                        db::rollback();
                                        return '没有此任务内容，无需审核';
                                    }

                                    $res = (new InventoryModel())->adjustInventory([
                                        'warehouse_id'        => $adjustInfo->warehouse_id,
                                        'platform_id'         => $adjustInfo->platform_id,
                                        'receive_platform_id' => $adjustInfo->receive_platform_id,
                                        'user_id'             => $adjustInfo->user_id,
                                        'sku_data'            => json_decode($adjustInfo->ext, true),
                                    ]);

                                    if ($res['code'] == 500) {
                                        db::rollback();
                                        return $res['msg'];
                                    }
                                }
//                            }
                        }
                    }else{
                        db::rollback();// 回调
                        return '您非审核人，无法审核';
                    }
                }else if ($task_find[0]['audit_method'] === 4){
                    // 无需审核
                    if (in_array($task_find[0]['class_id'], [2, 3, 4])){
                        if (isset($ext['request_id'])) {
                            $content = "任务：{$task_find[0]['name']}，审核已通过";
                            $request_status = Db::table('amazon_buhuo_request')->where('id', $ext['request_id'])->select('request_status')->first();
                            $update_goods = Db::table('goods_transfers')->where('order_no', $ext['request_id'])->update(['status' => 3,'push_time'=>date('Y-m-d H:i:s')]);
                            if ($request_status->request_status == 4) {
//                                $update_request = Db::table('amazon_buhuo_request')->where('id', $ext['request_id'])->update(['request_status' => 4]);
//                                if (!$update_request) {
//                                    db::rollback();// 回调
//                                    return '修改任务状态失败--amazon_buhuo_request表';
//                                }
                                //云仓补货计划则加入出库单队列
                                if($task_find[0]['class_id']==2) {
                                    //                                    $params['method'] = 'stockout.create';
                                    $params['order_no'] = $ext['request_id'];
                                    $params['type'] = 'B2BCK';
                                    $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                                    try {
                                        $cloud::outhouseJob($params);
                                        Redis::Lpush('cloud_outRequest',$ext['request_id']);
                                    } catch(\Exception $e){
                                        Redis::Lpush('out_house_fail',$ext['request_id']);
                                    }
                                }
//                                //发送站内消息给负责人
//                                $content = "任务：{$task_find[0]['name']}，审核已通过";
//                                //触发任务
//                                $arr = array();
//                                $arr['task_id'] = $data['task_id'];
//                                $task_trigger = $this->task_trigger($arr);
//                                if ($task_trigger != 1) {
//                                    return $task_trigger;
//                                }
                            }else{
                                db::rollback();// 回调
                                return '补货计划ID'.$ext['request_id'].'不为已审核待发货状态！';
                            }
                        }else{
                            db::rollback();// 回调
                            return '未给定补货计划标识！';
                        }

                        // 票据
                        if (in_array($task_find[0]['class_id'], [70])){
                            if(isset($ext['bill_id'])){
                                $billMdl = Db::table('financial_bill')->where('id', $ext['bill_id'])->first();
                                if(!empty($billMdl)){
                                    Db::table('financial_bill')->where('id', $billMdl->id)->update(['status' => 2, 'updated_at' => date('Y-m-d H:i:s')]);
                                }else{
                                    db::rollback();// 回调
                                    return '没有此任务内容，无需审核';
                                }
                            }
                        }
                    }
                }else if ($task_find[0]['audit_method'] === 5){
                    //审核方式为上级审核通过
                    $sql = "select Id
						from tasks_examine
						where 
						task_id={$data['task_id']} and `is_examine`=2";
                    $examine_next = json_decode(json_encode(db::select($sql)), true);
                    if (count($examine_next) == 0) {
                        //有：修改审核（是否可审核），发送站内消息给审核人；
                        //无:修改任务（任务状态），触发任务
                        //修改任务状态
                        $sql = "update tasks
							set state=3, time_examine='{$time_now}'
							where `Id` ={$data['task_id']}";
                        $task_update = db::update($sql);
                        if (!$task_update) {
                            db::rollback();// 回调
                            return '修改任务状态失败--tasks表';
                        }
                    }
                    $sql2 = "select user_id
						from tasks_examine
						where 
						`Id` = {$data['Id']}";
                    $audit = db::select($sql2);
                    $user_id = 0;
                }
                if($task_find[0]['class_id']==16||$task_find[0]['class_id']==17){
                    $tasks_examine = Db::table('tasks_examine')->where('task_id',$data['task_id'])->where('state','!=',3)->get()->toArray();
                    if(empty($tasks_examine)){
                        $up = Db::table('tasks')->where('Id',$data['task_id'])->update(['state'=>5]);
                    }
                }


            }
            if (isset($content)&&$task_find[0]['notice']==1) {
                if (isset($ext['request_id'])){
                    $content .=" , 补货计划id: ".$ext['request_id'];
                }
                if (isset($ext['order_id'])){
                    $content .=" , 下单计划id: ".$ext['order_id'];
                }
                if (isset($ext['contract_no'])){
                    $content .=" , 合同号: ".$ext['contract_no'];
                }
                if (isset($ext['bill_id'])){
                    $content .=" , 票据id: ".$ext['bill_id'];
                }
                if (isset($ext['bill_no'])){
                    $content .=" , 票据号: ".$ext['bill_no'];
                }
//            $user_mb = DB::table('users')->where('Id',$task_find[0]['user_fz'])->select('mobile','assistant')->first();
//            if(!empty($user_mb->assistant)){
//                $assistant = explode(",",$user_mb->assistant);
//            }
                $dingding = new \App\Models\BaseModel();
                $dingding->taskSend($task_find[0]['user_fz'],$content);
                $tiding = DB::table('tidings')->insertGetId(
                    ["user_fs" => 0, "user_js" => $task_find[0]['user_fz'], "title" => '任务审核', "content" => $content, "object_id" => $data['task_id'], "object_type" => 1, "type" => 1, "create_time" => $time_now]
                );
                if (!$tiding) {
                    db::rollback();// 回调
                    return '发送任务消息失败--tidings表';
                }
            }
            db::commit();// 确认
            return 1;
        }catch (\Exception $e){
            db::rollback();// 回调

            return $e->getMessage().'；'.$e->getLine().'；'.$e->getFile();
        }
    }

    /**
     * 触发节点任务
     * @param task_id 任务id
     * @logic 获取节点、节点任务 --> 修改节点状态（进行中） --> 第一节点任务开启、发送消息
     */
    public function task_trigger($data)
    {
        if (empty($data['task_id'])) {
            return 'task_id为空';
        }
        //获取任务名称
        $task = DB::table('tasks')->where('Id', $data['task_id'])->select('name','ext')->first();
        if($task->ext){
            $ext = json_decode($task->ext,true);
        }
        //获取节点
        $sql = "select *
                   from tasks_node
                   where `task_id`={$data['task_id']} and `state`=1
                   order by `Id` asc
                   limit 1";
        $node_find = json_decode(json_encode(db::select($sql)), true);
        if (empty($node_find)) {
            DB::table('tasks')->where('Id', $data['task_id'])->update(['state'=>5]);
            return 1;
        }

        //当前时间
        $time = time();
        $time_now = date('Y-m-d H:i:s', $time);

        //修改节点状态（进行中）
        $sql = "update tasks_node
					set `state`=2, time_state='{$time_now}'
					where `Id`={$node_find[0]['Id']}";
        $node_update = db::update($sql);
        if (!$node_update) {
            db::rollback();// 回调
            return '修改节点状态失败--tasks_node表';
        }

        //获取节点任务
        $sql = "select *
					from tasks_son
					where tasks_node_id={$node_find[0]['Id']} and f_id=0";
        $tasks_son_list = json_decode(json_encode(db::select($sql)), true);

        //第一节点任务开启、发送消息
        foreach ($tasks_son_list as $v) {
            //第一节点任务开启
//			$time_end_yj = date('Y-m-d H:i:s', strtotime("+{$v['day_yj']} day", $time));
//            $bb = $time + (3600 * 24 * $v['day_yj']);
//            $time_end_yj = date('Y-m-d H:i:s', $bb);
//            $sql = "update tasks_son
//						set state=2, time_state='{$time_now}', time_end_yj='{$time_end_yj}'
//						where `Id`={$v['Id']}";
//            $tasks_son_update = db::update($sql);
//            if (!$tasks_son_update) {
//                db::rollback();// 回调
//                return '修改节点任务失败--tasks_son表';
//            }

            //发送站内消息给第一节点人
            $content = $task->name . ",有新的任务: " . $v['task'];
            if(isset($ext['request_id'])){
                $content.=" , 补货计划id: ".$ext['request_id'];
            }
            if(isset($ext['order_id'])){
                $content.=" , 下单计划id: ".$ext['order_id'];
            }
            $tiding = DB::table('tidings')->insertGetId(
                ["user_fs" => 0, "user_js" => $v['user_id'], "title" => '新任务', "content" => $content, "object_id" => $v['task_id'], "object_type" => 1, "type" => 1, "create_time" => $time_now]
            );
            $dingding = new \App\Models\BaseModel();
            $dingding->taskSend($v['user_id'],$content);
//            if ($tiding) {
//                $this->redis_tiding($tiding, 0, intVal($v['user_id']), '新任务', $content, $v['task_id'], 1, 1);
//            }
        }
        return 1;
    }

////////////////////// 任务详情

    /**
     * 任务详情
     * @param task_id 任务id
     * @logic 任务基本信息、审核信息、节点、节点任务
     */
    public function task_info($data)
    {

        $ts = db::table('tasks')->where('id',$data['task_id'])->first();

//        if(!empty($ts)){
//            if($ts->is_deleted==1){
//                return '该任务已删除';
//            }
//        }

        //// 任务基本信息
        $sql = "select t.*, (select `account` from users where `Id`=t.user_fz) as account_fz
					from `tasks` t
					where t.Id = {$data['task_id']}";
        $task_find = json_decode(json_encode(db::select($sql)), true);
        $retuan = array();
        if (empty($task_find)) {
            return $retuan;
        }
       
        if(!empty($task_find[0]['file_fj'])) $task_find[0]['file_fj'] = json_decode($task_find[0]['file_fj'],true);
        if(!empty($task_find[0]['img'])) $task_find[0]['img'] = json_decode($task_find[0]['img'],true);

        $baseModel = new BaseModel();
        $userCsArr = explode(',', $task_find[0]['user_cs']);
        $userCs = '';
        foreach ($userCsArr as $userId){
            $userCs .= $baseModel->GetUsers($userId)['account'].' ';
        }
        $task_find[0]['user_cs_name'] = $userCs;
        if (!empty($task_find[0]['ext'])) {
            if (isset(json_decode($task_find[0]['ext'], true)['request_id'])) {
                $request_id = json_decode($task_find[0]['ext'], true)['request_id'];
                $request_detail = Db::table('amazon_buhuo_detail as a')
                    ->leftjoin('shop as b', 'a.shop_id', '=', 'b.Id')
                    ->select('a.sku', 'b.country_id')
                    ->where('request_id', $request_id)
                    ->get()
                    ->toArray();
                $sku_array = array_column($request_detail, 'sku');
                if ($request_detail) {
                    $father_asin_data = Db::table('product_detail')->select('parent_asin')->whereIn('sellersku', $sku_array)->get()->toArray();
                    $father_asin_arr = array_unique(array_filter(array_column($father_asin_data, 'parent_asin')));
                    /*if(isset($father_asin_data->father_asin)){
                        $father_asin = $father_asin_data->father_asin;
                    }*/
                    if ($father_asin_arr) {
                        $task_find[0]['country_id'] = $request_detail[0]->country_id;
                        $task_find[0]['amazom_link'] = $father_asin_arr;
                    }
                }
            }

            if (is_array(json_decode($task_find[0]['ext'], true))) {
                $task_find[0]['ext'] = json_decode($task_find[0]['ext'], true);
            }
        }

        if (!empty($task_find[0]['shop_id'])){
            $baseModel = new BaseModel();
            $shop = $baseModel->GetShop($task_find[0]['shop_id']);
            $task_find[0]['country_id'] = $shop['country_id'] ?? 0;
        }

        //// 审核信息
        $sql = "select user_id
					from tasks_examine
					where task_id = {$data['task_id']}";
        $tasks_examine = json_decode(json_encode(db::select($sql)), true);

        //// 节点、节点任务
        $sql = "select n.Id as n_id, n.task_id as n_task_id, n.name as n_name, n.state as n_state,
						n.time_state as n_time_state, n.time_end as n_time_end, n.circulation, ts.*
					from tasks_node n
					left join (select t.*, u.account, u.phone, u.heard_img
									from tasks_son t
									left join users u on u.Id = t.user_id
								) ts on ts.tasks_node_id = n.Id
					where n.task_id={$data['task_id']}
					order by n_id asc";
        $tasks_node_list = json_decode(json_encode(db::select($sql)), true);
//        if (empty($tasks_node_list)) {
//            return '任务节点不存在';
//        }

        $node = array();
        $node_ids = array();
        if(!empty($tasks_node_list)){
            //处理数据
            foreach ($tasks_node_list as $k => $v) {
                //所在位置
                $aa = array_search($v['n_id'], $node_ids);//array_search：变量是否在数组中，并返回所在位置
                //新增节点
                if ($aa === false) {
                    $arr = array();
                    $arr['Id'] = $v['n_id'];
                    $arr['task_id'] = $v['n_task_id'];
                    $arr['name'] = $v['n_name'];
                    $arr['circulation'] = $v['circulation'];
                    $arr['state'] = $v['n_state'];
                    $arr['time_state'] = $v['n_time_state'];
                    $arr['time_end'] = $v['n_time_end'];
                    $arr['node_task_data'] = array();
                    if ($v['circulation'] == 1) {
                        $arr['cir_name'] = '单人完成流转';
                    } else {
                        $arr['cir_name'] = '全部完成流转';
                    }
                    $node[] = $arr;
                    $node_ids[] = $v['n_id'];
                }

                //新增节点任务
                $arr = array();
                $arr['Id'] = $v['Id'];
                $arr['task_id'] = $v['task_id'];
                $arr['tasks_node_id'] = $v['tasks_node_id'];
                $arr['f_id'] = $v['f_id'];
                $arr['task'] = $v['task'];
                $arr['user_id'] = $v['user_id'];
                $arr['day_yj'] = $v['day_yj'];
                $arr['state'] = $v['state'];
                $arr['feedback_type'] = $v['feedback_type'];
                $arr['feedback_content'] = $v['feedback_content'];
                $arr['feedback_content2'] = $v['feedback_content2'];
                $arr['time_state'] = $v['time_state'];
                $arr['time_end_yj'] = $v['time_end_yj'];
                $arr['time_end_sj'] = $v['time_end_sj'];
                $arr['create_time'] = $v['create_time'];

                $arr['account'] = $v['account'];
                $arr['phone'] = $v['phone'];
                $arr['heard_img'] = $v['heard_img'];

                //当前所在位置
                $bb = array_search($v['n_id'], $node_ids);
                $node[$bb]['node_task_data'][] = $arr;
            }
        }

        $classId = $task_find[0]['class_id'] ?? 0;
        $examineId = [];
        if (!empty($classId)){
            $classMdl = db::table('task_class')
                ->where('id', $classId)
                ->first();
            if (!empty($classMdl->examine_id)){
                $examineId = explode(',', $classMdl->examine_id);
                $examineId = array_map(function ($value){ return intval($value);}, $examineId);
            }
        }
//        $ext = json_decode($task_find[0]['ext'], true);
//        if (in_array($classId, [56, 50, 29])){
//            if (isset($ext['adjust_id'])){
//                $adjustMdl = db::table('adjust_inventory_platform')
//                    ->where('id', $ext['adjust_id'])
//                    ->first();
//                if (!empty($adjustMdl)){
//                    $detail = json_decode($adjustMdl->ext, true);
//                    $customSkuIds = array_column($detail, 'custom_sku_id');
//                    $customSkuArr = DB::table('self_custom_sku')
//                        ->select('id', 'custom_sku', 'old_custom_sku', 'spu_id')
//                        ->whereIn('id', $customSkuIds)
//                        ->get()
//                        ->keyBy('id');
//                    $spuIds = $customSkuArr->pluck('spu_id');
//                    $threeCateIds = DB::table('self_spu')->whereIn('id', $spuIds)->pluck('three_cate_id')->toArray();
//                    $threeCateIds = array_unique($threeCateIds);
//                    if (count($threeCateIds) > 1) {
//                        return ['code' => 500, 'msg' => '只能调同一产品类目'];
//                    }
//
//                    $userIds = DB::table('product_cate')
//                        ->where('type', 2)
//                        ->where('platform_id', $adjustMdl->platformId)
//                        ->whereRaw("find_in_set({$threeCateIds[0]},`cate_ids`)")
//                        ->value('user_ids');
//
//                    $operateUserIds = explode(',', $userIds);
//                    $examineId = array_merge($examineId, $operateUserIds);
//                }
//            }
//        }

        $task_find[0]['examine_id'] = $examineId;
        $retuan['basic'] = $task_find[0];
        $retuan['basic']['examine'] = $tasks_examine;
        $retuan['node'] = $node;
        return $retuan;
    }

    /**
     * 编辑节点任务
     * @param Id 节点任务id
     */
    public function node_task_update($data)
    {
        // 获取节点任务
        $sql = "select *
					from tasks_son
					where `Id` = {$data['Id']}";
        $tasks_son_find = json_decode(json_encode(db::select($sql)), true);
        if (empty($tasks_son_find)) {
            return '节点任务不存在';
        } else if ($tasks_son_find[0]['state'] == 3) {
            return '节点任务已完成，不能编辑';
        } else if ($tasks_son_find[0]['state'] == 4) {
            return '节点任务已放弃，不能编辑';
        }

        $set = '';
        //task 任务
        if (!empty($data['task'])) {
            $set .= ",task='{$data['task']}'";
        }
        //user_id 执行人
        if (!empty($data['user_id'])) {
            $set .= ",user_id={$data['user_id']}";
        }
        //day_yj 预计完成天数
        if (!empty($data['day_yj'])) {
            //预计结束时间
            if ($data['state'] != '1') {
//				$data['time_end_yj'] = date('Y-m-d H:i:s', strtotime("+{$data['day_yj']} day", strtotime($data['time_state'])));
                $bb = strtotime($data['time_state']) + (3600 * 24 * $data['day_yj']);
                $data['time_end_yj'] = date('Y-m-d H:i:s', $bb);;

                $set .= ",time_end_yj='{$data['time_end_yj']}'";
            }

            $set .= ",day_yj={$data['day_yj']}";
        }

        $set = substr($set, 1);
        $sql = "update tasks_son
					set {$set}
					where `Id` = {$data['Id']}";
        $update = db::update($sql);
        if ($update === false) {
            return '编辑失败';
        }

        // 发送站内消息    节点任务进行中，且执行人有更换
        if ($tasks_son_find[0]['state']!= 3 && $tasks_son_find[0]['user_id'] != $data['user_id']) {
            $content = "您有新的任务，情尽快处理！";
            $tiding = DB::table('tidings')->insertGetId(
                ["user_fs" => 0, "user_js" => $data['user_id'], "title" => '新任务', "content" => $content, "object_id" => $data['task_id'], "object_type" => 1, "type" => 1, "create_time" => now()]
            );
            $dingding = new \App\Models\BaseModel();
            $dingding->taskSend($data['user_id'],$content);
//            if ($tiding) {
//                $this->redis_tiding($tiding, 0, intVal($data['user_id']), '新任务', $content, $data['task_id'], 1, 1);
//            }
        }

        return $data;
    }

    /**
     * 节点任务--（完成、放弃）
     * @param Id 节点任务id
     * @param state 状态：1.未开始、2.进行中、3.已完成、4.已放弃
     * @param feedback_type 反馈类型：1.文字、2.图片、3.文件
     * @param feedback_content 反馈内容
     * @logic  1、检测是否已修改过状态
     *         2、修改节点任务状态
     *         3、该节点下是否还有任务没做完
     *             未都完成：完
     *             都已完成：修改节点状态、结束时间
     *                      是否是最后一个节点
     *                          是：结束时间、修改任务状态，发站内消息给负责人提示验收
     *                          否：触发下一节点
     */
    public function task_son_complete($data)
    {
        $data['feedback_content'] = isset($data['feedback_content'])?$data['feedback_content']:'';
        //// 1、检测是否已修改过状态
        // 获取节点任务
//        var_dump($data);die;
        db::beginTransaction();
        $sql = "select *
					from tasks_son
					where `Id` = {$data['Id']}";
        $tasks_son_find = json_decode(json_encode(db::select($sql)), true);
        if (empty($tasks_son_find)) {
            db::rollback();
            return '节点任务获取失败';
        } else if ($tasks_son_find[0]['state'] == 1) {
            db::rollback();
            return '该节点任务未开始';
        } else if ($tasks_son_find[0]['state'] == 3) {
            DB::table('tasks_son')->where('Id', $data['Id'])->update(['time_end_sj'=>date('Y-m-d H:i:s')]);
            db::commit();
            return 1;
        } else if ($tasks_son_find[0]['state'] == 4) {
            db::rollback();
            return '该节点任务已被放弃';
        }
        $tasks_node_id = $tasks_son_find[0]['tasks_node_id'];
        $node_sql = "select *
					from tasks_node
					where `Id` = {$tasks_node_id}";
        $tasks_node_find = json_decode(json_encode(db::select($node_sql)), true);
        $task = DB::table('tasks')->where('Id', $tasks_son_find[0]['task_id'])->select('name', 'class_id', 'ext', 'audit_method')->first();
        if($task->ext){
            $ext = json_decode($task->ext, true);
        }
        //当前时间
        $time = time();
        $time_now = date('Y-m-d H:i:s', $time);
        if ($data['state'] == 4) {
            $update_status = DB::table('tasks')->where('Id', $tasks_son_find[0]['task_id'])->update(['state' => 6]);
            if (in_array($task->class_id, [2,3,4, 124, 127])) {
                $update_plan = DB::table('amazon_buhuo_request')->where('id', $ext['request_id'])->update(['request_status' => 1]);
                $goods = DB::table('goods_transfers')->where('order_no', '=', $ext['request_id'])->select('is_push')->first();
                if($goods->is_push==4){
                    return $this->back('订单已开始流转，无法取消', '500');
                }

                DB::table('goods_transfers')->where('order_no', '=', $ext['request_id'])->update(['is_push' => -1,'status'=>-1]);
            }
            if ($task->class_id == 19) {
                $update_order = DB::table('amazon_place_order_task')->where('id', $ext['order_id'])->update(['status' => -1]);
            }
            if ($task->audit_method == 3) {
                $update_audit = DB::table('tasks_examine')->where('task_id', $tasks_son_find[0]['task_id'])->update(['is_examine' => 1, 'state' => 3]);
            }
            $sql = "update tasks_son
					set `state`={$data['state']}, feedback_type={$data['feedback_type']}, feedback_content='{$data['feedback_content']}', time_end_sj='{$time_now}'
					where `Id` = {$data['Id']}";
            $tasks_son_update = db::update($sql);
            $tasks_node_update = DB::table('tasks_node')->where('task_id', $tasks_son_find[0]['task_id'])->update(['state' => 3]);
            $tasks_node_update2 = DB::table('tasks_son')->where('task_id', $tasks_son_find[0]['task_id'])->where('Id', '!=', $data['Id'])->update(['state' => 3]);
            db::commit();
            return 1;
        }

        if ($tasks_node_find[0]['circulation'] == 1) {
            $sql = "update tasks_son
					set `state`={$data['state']}, feedback_type={$data['feedback_type']}, feedback_content='{$data['feedback_content']}', time_end_sj='{$time_now}'
					where `tasks_node_id` in ({$tasks_node_id})";
            $tasks_son_update = db::update($sql);
            if (!$tasks_son_update) {
                db::rollback();
                return '修改节点任务失败';
            }
            if (isset($tasks_node_find[0]['name']) && $tasks_node_find[0]['name'] == '执行策略，反馈进度'){
                if (empty($tasks_node_find[0]['task_id'])){
                    db::rollback();
                    return '未查询到任务Id！';
                }
                $taskMdl = db::table('tasks')
                    ->where('Id', $tasks_node_find[0]['task_id'])
                    ->first();
                if (empty($taskMdl)){
                    db::rollback();
                    return '未查询到任务！';
                }
                if ($taskMdl->class_id != 134){
                    db::rollback();
                    return '非asin策略任务！';
                }
                $ext = json_decode($taskMdl->ext, true);
                if (!isset($ext['request_id'])){
                    db::rollback();
                    return '未给定策略任务标识！';
                }
                $update = db::table('sku_strategy_log')
                    ->where('task_id', $ext['request_id'])
                    ->update([
                       'status' => 1,
                        'end_time' => date('Y-m-d H:i:s', microtime(true))
                    ]);
            }
        } else {
            //// 修改节点任务：状态、反馈类型、反馈内容、实际结束时间
            $sql = "update tasks_son
					set `state`={$data['state']}, feedback_type={$data['feedback_type']}, feedback_content='{$data['feedback_content']}', time_end_sj='{$time_now}'
					where `Id` = {$data['Id']}";
            $tasks_son_update = db::update($sql);
            if (!$tasks_son_update) {
                db::rollback();
                return '修改节点任务失败';
            }

            //// 该节点下是否还有任务没做完
            $sql = "select *
					from tasks_son
					where tasks_node_id = {$tasks_son_find[0]['tasks_node_id']} and `state` in (1,2)";
            $tasks_son_no = json_decode(json_encode(db::select($sql)), true);
            if (count($tasks_son_no) > 0) {
                // 该节点还有未完成的节点任务
                db::commit();
                return 1;
            }
        }


        // 都已完成：修改节点状态、结束时间
        $sql = "update tasks_node
					set `state`=3, `time_end`='{$time_now}'
					where `Id` = {$tasks_son_find[0]['tasks_node_id']}";
        $tasks_node_update = db::update($sql);
        if (!$tasks_node_update) {
            db::rollback();
            return '修改节点失败';
        }

        //// 是否是最后一个节点
        $sql = "select *
                   from tasks_node
                   where `task_id`={$tasks_son_find[0]['task_id']} and `state`=1
                   order by `Id` asc
                   limit 1";
        $node_find = json_decode(json_encode(db::select($sql)), true);
        if (count($node_find) > 0) {
            // 否：触发下一节点
            //触发任务
            $arr = array();
            $arr['task_id'] = $tasks_son_find[0]['task_id'];
            $task_trigger = $this->task_trigger($arr);
            if ($task_trigger != 1) {
                db::commit();
                return $task_trigger;
            }

        } else if (count($node_find) === 0) {
            //// 是：结束时间、修改任务状态，发站内消息给负责人提示验收
            // 结束时间、修改任务状态
            $sql = "update tasks
						set `state`=4, `time_end`='{$time_now}'
						where `Id` = {$tasks_son_find[0]['task_id']}";
            $task_update = db::update($sql);
            if (!$task_update) {
                db::rollback();
                return '修改任务失败';
            }
            // 发站内消息给负责人提示验收
            $sql = "select *
						from tasks
						where `Id` = {$tasks_son_find[0]['task_id']}";
            $task_find = json_decode(json_encode(db::select($sql)), true);
            $content = "任务：{$task_find[0]['name']}，请验收！";
            if(isset($ext['request_id'])){
                $content .=" , 补货计划id: ".$ext['request_id'];
            }
            $tiding = DB::table('tidings')->insertGetId(
                ["user_fs" => 0, "user_js" => $task_find[0]['user_fz'], "title" => '任务验收', "content" => $content, "object_id" => $task_find[0]['Id'], "object_type" => 1, "type" => 1, "create_time" => $time_now]
            );
            $dingding = new \App\Models\BaseModel();
            $dingding->taskSend($task_find[0]['user_fz'],$content);
//            if ($tiding) {
//                $this->redis_tiding($tiding, 0, intVal($task_find[0]['user_fz']), '任务验收', $content, $task_find[0]['Id'], 1, 1);
//            }
        }
        db::commit();
        return 1;
    }

    /**
     * 编辑任务
     * @parma Id 任务id
     * @param name 任务名称
     * @param user_fz 负责人
     * @Parma desc 任务描述
     */
    public function task_update($data)
    {
        $set = "";
        //name 任务名称
        if (!empty($data['name'])) {
            // 验证唯一
            $sql = "select `Id`
						from `tasks`
						where `Id`!={$data['Id']} and `name` = '{$data['name']}'";
            $task_find = json_decode(json_encode(db::select($sql)), true);
            if (!empty($task_find)) {
                return '任务名称已被使用，不能重复！';
            }

            $set .= ",`name`='{$data['name']}'";
        }
        //user_fz 负责人
        if (!empty($data['user_fz'])) {
            $set .= ",`user_fz`={$data['user_fz']}";
        }
        //file_fj 附件
        if (!empty($data['file_fj'])) {
            $data['file_fj'] = json_encode($data['file_fj']);
            $set .= ",`file_fj`='{$data['file_fj']}'";
        }
        //desc 任务描述
        if (!empty($data['desc'])) {
            $set .= ",`desc`='{$data['desc']}'";
        }

        if ($set == '') {
            return '更新条件为空';
        }
        $set = substr($set, 1);

        $sql = "update tasks
					set {$set}
					where `Id` = {$data['Id']}";
        $update = db::update($sql);
        if ($update !== false) {
            return 1;
        } else {
            return '更新失败';
        }
    }

    /**
     * 任务消息
     * @param task_id 任务id
     */
//    public function tasks_news_list($data)
//    {
//        $where = "1=1";
//        //task_id 任务id
//        if (!empty($data['task_id'])) {
//            $where .= " and n.task_id={$data['task_id']}";
//        }
//
//        $sql = "select n.*, u_fs.account as account_fs, u_fs.heard_img as heard_img_fs,
//						if(n.user_js, (select account from users where `Id`=n.user_js), '') as account_js
//					from tasks_news n
//					inner join users u_fs on u_fs.Id = n.user_fs
//					where {$where}
//					order by n.Id desc";
//        $list = json_decode(json_encode(db::select($sql)), true);
//
//        $return['list'] = $list;
//        return $return;
//    }
//
//    /*
//     * 新增任务消息
//     * @param task_id 任务id
//     * @param task_name 任务名称
//     * @param user_fs 发送人
//     * @param user_js 接收人
//     * @param type 类型：1.文字、2.图片、3.文件
//     * @param content 内容
//     * @logic 新增任务消息
//     *          如有接收人，给接收人发送站内消息
//     */
//    public function task_new_add($data)
//    {
//        // 新增任务消息
//        $field = 'create_time';
//        $insert = 'now()';
//        $arr = array('task_id', 'user_fs', 'user_js', 'type', 'content','msg_type');
//        foreach ($data as $k => $v) {
//            if (in_array($k, $arr)) {
//                $field .= ",`{$k}`";
//                $insert .= is_numeric($v) ? ",{$v}" : ",'{$v}'";
//            }
//        }
//        $sql = "insert into tasks_news({$field}) values ({$insert})";
//        $add = db::insert($sql);
//        if (!$add) {
//            return '新增任务内消息失败';
//        }
//        // 如有接收人，给接收人发送站内消息
//        if (!empty($data['user_js'])) {
//            $content = "任务：{$data['task_name']}，有发送给您的消息！";
//            $tiding = DB::table('tidings')->insertGetId(
//                ["user_fs" => $data['user_fs'], "user_js" => $data['user_js'], "title" => '任务内消息', "content" => $content, "object_id" => $data['task_id'], "object_type" => 1, "type" => 1, "create_time" => now()]
//            );
//            if ($tiding) {
//                $this->redis_tiding($tiding, intVal($data['user_fs']), intVal($data['user_js']), '任务内消息', $content, $data['task_id'], 1, 1);
//            }
//        }
//        return 1;
//    }

    public function tasks_news_list($data)
    {
        $tasksNews = db::table('tasks_news');
        $where = "1=1";
        //task_id 任务id
        if (!empty($data['task_id'])) {
            $tasksNews = $tasksNews->where('task_id', $data['task_id']);
        }

//        $sql = "select n.*, u_fs.account as account_fs, u_fs.heard_img as heard_img_fs,
//                if(n.user_js, (select account from users where `Id`=n.user_js), '') as account_js
//             from tasks_news n
//             inner join users u_fs on u_fs.Id = n.user_fs
//             where {$where}
//             order by n.Id desc";
//        $list = json_decode(json_encode(db::select($sql)), true);
        $tasksNews = $tasksNews->orderBy('Id', 'DESC')->get();
        $base = new BaseModel();
        foreach ($tasksNews as $item){
            $item->account_fs = $base->GetUsers($item->user_fs)['account'] ?? '';
            $userJs = explode(',', $item->user_js);
            $userJsName = [];
            foreach ($userJs as $userId){
                $userJsName[] = $base->GetUsers($userId)['account'] ?? '';
            }
            $item->account_js = $userJsName;
            $item->file = json_decode($item->file, true) ?? [];
            $item->img = json_decode($item->img, true) ?? [];
            $item->content = !empty($item->content) ? $item->content : '';
        }
        $return['list'] = $tasksNews;
        return $return;
    }

    /*
     * 新增任务消息
     * @param task_id 任务id
     * @param task_name 任务名称
     * @param user_fs 发送人
     * @param user_js 接收人
     * @param type 类型：1.文字、2.图片、3.文件
     * @param content 内容
     * @logic 新增任务消息
     *          如有接收人，给接收人发送站内消息
     */
    public function task_new_add($data)
    {
        // 新增任务消息
        if (!isset($data['task_id']) || empty($data['task_id'])){
            return "未给定任务标识！";
        }
        if (!isset($data['user_fs']) || empty($data['user_fs'])){
            return "未给定发送人标识！";
        }
//        if (!isset($data['user_js']) || empty($data['user_js'])){
//            return "未给定接收人标识！";
//        }
        if (!isset($data['msg_type']) || empty($data['msg_type'])){
            return "未给定点评类型标识！";
        }
        if ((!isset($data['content']) || empty($data['content'])) && (!isset($data['file']) || empty($data['file'])) && (!isset($data['img']) || empty($data['img']))){
            return "不可发送空消息！";
        }
        $insert = [
            'task_id' => $data['task_id'],
            'user_fs' => $data['user_fs'],
            'user_js' => !empty($data['user_js']) ? implode(',', $data['user_js']) : null,
            'content' => $data['content'],
            'create_time' => date('Y-m-d H:i:s', time()),
            'msg_type' => $data['msg_type'],
            'file' => json_encode($data['file'] ?? []),
            'img' => json_encode($data['img'] ?? [])
        ];
        $add = db::table('tasks_news')->insert($insert);
        if (!$add) {
            return '新增任务内消息失败';
        }
        if (!isset($data['user_js']) || empty($data['user_js'])) {
            return 1;
        }

        // 如有接收人，给接收人发送站内消息
        $content = "任务：{$data['task_name']}，有发送给您的消息！";
        foreach ($data['user_js'] as $userId) {
            $tiding = DB::table('tidings')->insertGetId(
                ["user_fs" => $data['user_fs'], "user_js" => $userId, "title" => '任务内消息', "content" => $content, "object_id" => $data['task_id'], "object_type" => 1, "type" => 1, "create_time" => now()]
            );
            if ($tiding) {
                $this->redis_tiding($tiding, intVal($data['user_fs']), intVal($userId), '任务内消息', $content, $data['task_id'], 1, 1);
            }
        }

        if ($data['send_type'] == 1) {
            return 1;
        }

        $email = DB::table('users')->select('email')->whereIn('id', $data['user_js'])->get()->pluck('email')->toArray();
        $email = array_filter($email);
        if (!$email) {
            return 1;
        }
        $data['email'] = $email;
        try {
            $content = "任务：{$data['task_name']} \n内容：{$data['content']}";
            Mail::raw($content, function ($message) use ($data) {
                $message->subject('任务内消息');//标题
                foreach ($data['email'] as $v) {
                    $message->to($v);//收件人
                }
                if (isset($data['img']) && !empty($data['img'])) {
                    foreach ($data['img'] as $v) {
                        $message->attach($v);//附件
                    }
                }
                if (isset($data['file']) && !empty($data['file'])) {
                    foreach ($data['file'] as $v) {
                        $message->attach($v);//附件
                    }
                }
            });
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }
        return 1;
    }

    /*
     * 删除任务消息
     * @param Id 任务消息id
     */
    public function task_new_del($data)
    {
        // 获取任务消息
        $sql = "select *
					from tasks_news
					where `Id` = {$data['Id']}";
        $find = json_decode(json_encode(db::select($sql)), true);
        if (empty($find)) {
            return 1;
        }

        // 删除任务消息
        $sql = "delete
					from tasks_news
					where `Id`={$data['Id']}";
        $del = db::delete($sql);
        if (!$del) {
            return '删除任务消息失败';
        }

        // 删除七牛云文件
        if (in_array($find[0]['type'], array('2', '3'))) {
            $file_del = array();
            $file_url = explode('/', $find[0]['content']);
            $file_del[] = $file_url[(count($file_url) - 1)];
            //删除七牛云文件
            $Qiniu = new \App\Libs\wrapper\Qiniu();
            $Qiniu->file_del($file_del);
        }

        return 1;
    }

    /**
     * 新增节点任务
     * @logic 该节点是否已结束 --> 新增节点任务 --> 给执行人发送站内消息
     */
    public function node_task_add($data)
    {
        //// 该节点是否已结束
        $sql = "select `Id`, `state`
					from `tasks_node`
					where `Id` = {$data['tasks_node_id']}";
        $tasks_node_find = json_decode(json_encode(db::select($sql)), true);
        if (empty($tasks_node_find)) {
            return '任务节点不存在';
        } else if ($tasks_node_find[0]['state'] == 3) {
            return '该任务节点已结束';
        }

        //// 新增节点任务
        $time = time();
        $time_now = date('Y-m-d H:i:s', $time);

        $filed = "`task_id`, `tasks_node_id`, `task`, `user_id`, `day_yj`, `create_time`";
        $insert = "{$data['task_id']}, {$data['tasks_node_id']}, '{$data['task']}', {$data['user_id']}, {$data['day']}, '{$time_now}'";
        if ($tasks_node_find[0]['state'] == 1) {
            // 节点状态：未开始
            $filed .= ",`state`";
            $insert .= ",1";
        } else if ($tasks_node_find[0]['state'] == 2) {
            // 节点状态：进行中
            $time_end_yj = date('Y-m-d H:i:s', strtotime("+{$data['day']} day", $time));

            $filed .= ",`state`, `time_state`, `time_end_yj`";
            $insert .= ",2, '{$time_now}', '{$time_end_yj}'";
        }

        $sql = "insert into tasks_son({$filed}) values ({$insert})";
        $tasks_son_add = db::insert($sql);
        if (!$tasks_son_add) {
            return '新增节点任务失败';
        }

        //发送站内消息给审核人
        if ($tasks_node_find[0]['state'] == 2) {
            $content = "您有新的任务，情尽快处理！";
            $tiding = DB::table('tidings')->insertGetId(
                ["user_fs" => 0, "user_js" => $data['user_id'], "title" => '新任务', "content" => $content, "object_id" => $data['task_id'], "object_type" => 1, "type" => 1, "create_time" => $time_now]
            );
            $dingding = new \App\Models\BaseModel();
            $dingding->DingdingSend($data['user_id'],$content);
//            if ($tiding) {
//                $this->redis_tiding($tiding, 0, intVal($data['user_id']), '新任务', $content, $data['task_id'], 1, 1);
//            }
        }
        return 1;
    }

    /**
     * 验收任务
     * @param task_id 任务id
     */
    public function task_determine($data)
    {
        //// 该节点是否已结束
        db::beginTransaction();
        $sql = "update tasks
		            set `state`=5, time_end=now()
		            where `Id` = {$data['task_id']}";
        $update = db::update($sql);
        if ($update) {
            $select_sql = "select class_id,ext
                        from tasks
		                where `Id` = {$data['task_id']}";
            $select = db::select($select_sql);
            if (!empty($select)) {
                if ($select[0]->class_id == 3 || $select[0]->class_id == 4) {
                    $ext = json_decode($select[0]->ext, true);
                    $request_id = $ext['request_id'];
                    $update_sql = "update amazon_buhuo_request
		            set `request_status`=10
		            where `id` = {$request_id}";
                    $update_status = db::update($update_sql);
                    if (!$update_status) {
                        db::rollback();// 回调
                        return '验收失败';
                    }
                }
            }
            db::commit();
            return 1;
        } else {
            db::rollback();// 回调
            return '验收失败';
        }
    }





////////////////////// 新增任务页面

    /**
     * 新增任务模板
     * @param type_mb 模板类型：1.财务模板、2.人事模板、3.产品开发
     * @parma name 任务模板名称
     * @param user_fz 负责人
     * @param desc 任务描述
     * @param examine 审核人  数组
     * @param node 节点、节点任务   数组
     *              name 节点名称
     *              node_task_data 节点任务     数组
     *                      user_id 执行人
     *                      day 预计完成天数
     *                      task 任务
     */
    public function task_template_add($data)
    {
        //新增任务，验证唯一 --> 新增任务审核 --> 新增节点、节点任务
        //// 新增任务模板
        // 验证唯一
        $sql = "select `Id`
					from `tasks`
					where `name` = '{$data['name']}'";
        $task_find = json_decode(json_encode(db::select($sql)), true);
        if (!empty($task_find)) {
            return '名称已被使用，不能重复！';
        }

        // 新增任务模板
        db::beginTransaction();    //开启事务

        $arr = array();
        $arr['name'] = $data['name'];
        $arr['user_fz'] = $data['user_fz'];
        $arr['user_cj'] = isset($data['user_cj']) ? $data['user_cj'] : '';
        $arr['file_fj'] = isset($data['file_fj']) ? json_encode($data['file_fj']) : '';
        $arr['user_cs'] = empty($data['user_cs']) ? '' : implode(',', $data['user_cs']);;
        $arr['desc'] = isset($data['desc']) ? $data['desc'] : '';
        $arr['state'] = 1;
        $arr['type'] = 2;
        $arr['type_mb'] = $data['type_mb'];
        $arr['audit_method'] = $data['audit_method'];
        $arr['create_time'] = date('Y-m-d H:i:s', time());
        if (isset($data['class_id'])) {
            $arr['class_id'] = $data['class_id'];
        }
        if (isset($data['ext'])) {
            $arr['ext'] = json_encode($data['ext']);
        }
        $task_add = db::table('tasks')->insertGetId($arr);
        if (!$task_add) {
            db::rollback();// 回调
            return '新增任务失败--tasks表';
        }

        if(!empty($data['node'])){
            //// 新增节点、节点任务
            foreach ($data['node'] as $k => $v) {
                // 新增节点
                $arr = array();
                $arr['task_id'] = $task_add;
                $arr['name'] = $v['name'];
                $arr['circulation'] = $v['circulation'];
                $node_add = db::table('tasks_node')->insertGetId($arr);
                if (!$node_add) {
                    db::rollback();// 回调
                    return '新增任务节点失败--tasks_node表';
                }

                // 节点任务
                $insert = "";
                foreach ($v['node_task_data'] as $k1 => $v1) {
                    $insert .= ",({$task_add}, {$node_add}, '{$v1['task']}', {$v1['user_id']}, {$v1['day_yj']}, now())";
                }
                $insert = substr($insert, 1);
                $sql = "insert into tasks_son(`task_id`, `tasks_node_id`, `task`, `user_id`, `day_yj`, `create_time`) values {$insert}";
                $tasks_son_add = db::insert($sql);
                if (!$tasks_son_add) {
                    db::rollback();// 回调
                    return '新增节点任务失败--tasks_son表';
                }
            }
        }

        //// 新增任务审核
        if (isset($data['examine'])) {
            $insert = "";
            foreach ($data['examine'] as $k => $v) {
                $insert .= ",({$task_add}, {$v}, 1)";
            }
            $insert = substr($insert, 1);
            $sql = "insert into tasks_examine(`task_id`, `user_id`, `is_examine`) values {$insert}";
            $tasks_examine_add = db::insert($sql);
            if (!$tasks_examine_add) {
                db::rollback();// 回调
                return '新增任务审核失败--tasks_examine表';
            }
        }

        db::commit();// 确认
        return 1;
    }

    /**
     * 编辑任务模板
     * @param Id 任务模板id
     * @param type_mb 模板类型：1.财务模板、2.人事模板、3.产品开发
     * @parma name 任务模板名称
     * @param user_fz 负责人
     * @param desc 任务描述
     * @param examine 审核人  数组
     * @param node 节点、节点任务   数组
     *              name 节点名称
     *              node_task_data 节点任务     数组
     *                      user_id 执行人
     *                      day 预计完成天数
     *                      task 任务
     */
    public function task_template_update($data)
    {
        // 验证唯一
        $sql = "select `Id`
					from `tasks`
					where `Id`!={$data['Id']} and `name` = '{$data['name']}'";
        $task_find = json_decode(json_encode(db::select($sql)), true);
        if (!empty($task_find)) {
            return '名称已被使用，不能重复！';
        }

        //开启事务
        db::beginTransaction();

        //// 更新任务信息
        if (empty($data['user_cs'])) {
            $data['user_cs'] = '';
        } else {
            $data['user_cs'] = implode(',', $data['user_cs']);
        }

        $data['user_fz'] = $data['user_fz'] ?: 0;
        if (isset($data['ext'])) {

            $update = array();
            $update['name'] = $data['name'];
            $update['user_fz'] = $data['user_fz'];
            $update['desc'] = $data['desc'];
            $update['user_cs'] = $data['user_cs'];
            $update['file_fj'] = isset($data['file_fj'])?json_encode($data['file_fj']):'';
            $update['name'] = $data['name'];
            $update['type_mb'] = $data['type_mb'];
            $update['class_id'] = $data['class_id'];
            $ext = json_encode($data['ext']);
            $update['ext'] = $ext;
            $task_update = TaskModel::where('Id', $data['Id'])->update($update);

        } else {
            $sql = "update tasks
					set `name`='{$data['name']}', `user_fz`={$data['user_fz']}, `desc`='{$data['desc']}', `user_cs`='{$data['user_cs']}'
					  , `type_mb`={$data['type_mb']}, `class_id`={$data['class_id']},`audit_method`={$data['audit_method']}
					where `Id` = {$data['Id']}";
            $task_update = db::update($sql);

        }
        if ($task_update === false) {
            return '更新任务信息失败';
        }

        //// 删除：任务审核、任务节点、节点任务
        $sql = "delete te, n, ts
					from tasks t
					left join tasks_examine te on te.task_id = t.Id
					inner join tasks_node n on n.task_id = t.Id
					inner join tasks_son ts on ts.task_id = t.Id
					where t.`Id`={$data['Id']}";
        $del = db::delete($sql);

        //// 新增节点、节点任务
        if(isset($data['node'])){
            foreach ($data['node'] as $k => $v) {
                // 新增节点
                $arr = array();
                $arr['task_id'] = $data['Id'];
                $arr['name'] = $v['name'];
                $arr['circulation'] = $v['circulation'];
                $node_add = db::table('tasks_node')->insertGetId($arr);
                if (!$node_add) {
                    db::rollback();// 回调
                    return '新增任务节点失败--tasks_node表';
                }

                // 节点任务
                $insert = "";
                foreach ($v['node_task_data'] as $k1 => $v1) {
                    $insert .= ",({$data['Id']}, {$node_add}, '{$v1['task']}', {$v1['user_id']}, {$v1['day_yj']}, now())";
                }
                $insert = substr($insert, 1);
                $sql = "insert into tasks_son(`task_id`, `tasks_node_id`, `task`, `user_id`, `day_yj`, `create_time`) values {$insert}";
                $tasks_son_add = db::insert($sql);
                if (!$tasks_son_add) {
                    db::rollback();// 回调
                    return '新增节点任务失败--tasks_son表';
                }
            }
        }

        //// 新增任务审核
        if (isset($data['examine'])) {
            DB::table('tasks_examine')->where('task_id',$data['Id'])->delete();
            $insert = "";
            foreach ($data['examine'] as $k => $v) {
                $insert .= ",({$data['Id']}, {$v}, 1)";
            }
            $insert = substr($insert, 1);
            $sql = "insert into tasks_examine(`task_id`, `user_id`, `is_examine`) values {$insert}";
            $tasks_examine_add = db::insert($sql);
            if (!$tasks_examine_add) {
                db::rollback();// 回调
                return '新增任务审核失败--tasks_examine表';
            }
        }

        db::commit();// 确认
        return 1;
    }

////////////////////// 我的任务

    /**
     * 我的任务列表--数据
     * @param user_id 执行人
     * @param task_name 任务名称
     * @param task 任务描述
     * @param time_end_yj 预计结束时间
     */
    public function task_me($data)
    {

        //// 获取任务
        $where = "t.type=1";
        // 过滤已删除的任务
        $where .= " and t.`is_deleted` = 0";
        //user_id 执行人
        if (!empty($data['user_id'])) {
            $where .= " and ts.`user_id`={$data['user_id']}";
        }
        //task_name 任务名称
        if (isset($data['task_name'])) {
            $where .= " and t.`name` like '%{$data['task_name']}%'";
        }
        //task 任务描述
        if (isset($data['task'])) {
            $where .= " and ts.`task` like '%{$data['task']}%'";
        }
        //task_keys 任务关键字
        if (isset($data['task_keys'])) {
            $where .= " and t.`ext` like '%{$data['task_keys']}%'";
        }
        //time_end_yj 预计结束时间
        if (!empty($data['time_end_yj'])) {
            $state_time = $data['time_end_yj'][0] . ' 00:00:00';
            $end_time = $data['time_end_yj'][1] . ' 23:59:59';
            $where .= " and ts.create_time>='{$state_time}' and ts.create_time<='{$end_time}'";
        }
        //class_id 任务分类
        if (!empty($data['class_id'])) {
            $classArr = implode(',',$data['class_id']);
            $where .= " and t.`class_id` in ($classArr)";
        }
        if (isset($data['task_id'])) {
            $where .= " and t.`Id`={$data['task_id']}";
        }
        // 是否筛选zityChen已审核
        if (isset($data['is_audit']) && !empty($data['is_audit'])){
            $taskExamine = $this->taskExamineModel::query()
                ->where('user_id', 14)
                ->where('state', 3)
                ->get();
            if ($taskExamine->isNotEmpty()){
                $taskIds = implode(',', array_column($taskExamine->toArray(), 'task_id'));
            }else{
                $taskIds = '';
            }
            $where .= "and t.Id in ({$taskIds})";
        }


//        $sql = "select ts.*, t.name as task_name,t.class_id,t.ext,t.desc,t.state as task_state,d.state as node_state,t.Id as tid

        //筛选负责人
        if (isset($data['user_fz'])) {
            $where .= " and t.`user_fz` in ({$data['user_fz']})";
        }

        $sql = "select ts.*, t.name as task_name,t.class_id,t.ext,t.desc,t.state as task_state,d.state as node_state,t.Id as tid,t.user_fz, t.user_cj
				       from tasks_son ts
				       inner join tasks t on t.Id = ts.task_id
				       inner join tasks_node d on d.Id = ts.tasks_node_id    
				       where {$where}
				       order by t.create_time asc";

 
        $list = json_decode(json_encode(db::select($sql)), true);
        $classId = array_column($list,'class_id');
        $classId = array_unique($classId);

        $task_class = DB::table('task_class')->select('id', 'title')->whereIn('id', $classId)->get();
        $task_class = json_decode(json_encode($task_class), true);
        $class_arr = array();
        //拼接任务分类名称
        foreach ($task_class as $cla) {
            $class_arr[$cla['id']] = $cla['title'];
        }

        $TaskClassModule = DB::table('task_class_module')->whereIn('class_id', $classId)->get()->toArray();
        $classModule = [];
        //拼接分类的module数组
        foreach ($TaskClassModule as $k=>$module){
            foreach ($classId as $id){
                if($module->class_id==$id){
                    $classModule[$module->class_id][$k] = ['id'=>$module->id,'label'=>$module->label,'name'=>$module->name,'type'=>$module->type,'api'=>$module->api
                        ,'class_id'=>$module->class_id,'api_id'=>$module->api_id,'api_label'=>$module->api_label,'api_param'=>$module->api_param];
                }
            }
        }
        //拼接任务的ext列表
        $extArr = [];
        $tasklist = array_column($list,'ext');
        foreach ($tasklist as $taskext){
            $extArr[] = json_decode($taskext);
        }
        //拼接补货计划任务id
        $requestArr = [];
        foreach ($extArr as $extVal){
            if(isset($extVal->request_id)){
                $requestArr[] = $extVal->request_id;
            }
        }
        $requestArr = array_unique($requestArr);
        //查询这些计划id的计划明细数据
        $request_data = DB::table('amazon_buhuo_detail as a')
            ->leftJoin('amazon_buhuo_request as b','a.request_id','=','b.id')
            ->select('a.request_id','a.request_num', 'a.transportation_mode_name', 'a.transportation_type','b.request_status','b.shop_id')
            ->whereIn('a.request_id',$requestArr)
            ->get()
            ->toArray();
        //拼接计划明细数据
        foreach ($request_data as $key=>$resVal){
            foreach ($requestArr as $requestId){
                if($requestId==$resVal->request_id){
                    $request_detail[$resVal->request_id][$key] = ['transportation_mode_name'=>$resVal->transportation_mode_name
                        ,'transportation_type'=>$resVal->transportation_type,'request_status'=>$resVal->request_status,'shop_id'=>$resVal->shop_id];
                    $all_num[$resVal->request_id][$key] = $resVal->request_num;
                }
            }
            $request_detail[$resVal->request_id] = array_values($request_detail[$resVal->request_id]);
            $all_num[$resVal->request_id] = array_values($all_num[$resVal->request_id]);
        }
        $taskIds = array_column($list, 'tid');
        $taskExamineMdl = DB::table('tasks_examine as te')
            ->leftJoin('users as u', 'te.user_id', '=', 'u.Id')
            ->whereIn('te.task_id', $taskIds)
            ->get(['te.*', 'u.account']);
        $taskExamineArr = []; // 审核人信息
        foreach ($taskIds as $task_id){
            $notAudit = []; // 未审核名单
            $audit = []; // 已审核名单
            foreach ($taskExamineMdl as $item){
                if ($task_id == $item->task_id){
                    // 未审核 1：待审核 2：已阅
                    if (in_array($item->state, [1, 2])){
                        $notAudit[] = $item->account;
                    }
                    if (in_array($item->state, [3, 4])){
                        $audit[] = $item->account;
                    }
                }
            }
            if (array_key_exists($task_id, $taskExamineArr)){
                $taskExamineArr[$task_id]['audit'] = array_merge($taskExamineArr[$task_id]['audit'], $audit);
                $taskExamineArr[$task_id]['not_audit'] = array_merge($taskExamineArr[$task_id]['not_audit'], $notAudit);
            }else{
                $taskExamineArr[$task_id] = [
                    'audit' => $audit,
                    'not_audit' => $notAudit
                ];
            }
        }
        //// 处理数据
        $arr = array();
        $arr['not_start'] = array();//未开始
        $arr['overdue'] = array();//已逾期
        $arr['not_overdue'] = array();//未逾期
        $arr['abandon'] = array();//已放弃
        $arr['complete'] = array();//已完成
        $baseModel = new BaseModel();


        if (!empty($list)){
            // 当前时间
            $time_now = date('Y-m-d H:i:s', time());
            foreach ($list as $v) {
                $v['created_author'] = $baseModel->GetUsers($v['user_cj'])['account'] ?? ''; // 任务创建人
                $v['class_name'] = '';
                if (array_key_exists($v['class_id'], $class_arr)) {
                    $v['class_name'] = $class_arr[$v['class_id']];
                }else{
                    $v['class_name'] = '';
                }
                $v['platform_name'] = '';
                // 审核人
                $v['auditor'] = implode(',', array_unique($taskExamineArr[$v['tid']]['audit']));
                $v['not_auditor'] = implode(',', array_unique($taskExamineArr[$v['tid']]['not_audit']));
                //负责人
                $v['user_fz_name'] = $baseModel->GetUsers($v['user_fz'])?$baseModel->GetUsers($v['user_fz'])['account']:'';
                $v['sku_count'] = 0;
                $v['sum'] = 0;
                if ($v['ext'] != null && $v['ext'] != '') {
                    $ext = json_decode($v['ext'], true);
                    $v['ext'] = $ext;
                    if (array_key_exists($v['class_id'], $classModule)) {
                        $v['clsss_module'] = $classModule[$v['class_id']];
                    }else{
                        $v['clsss_module'] = [];
                    }
                    if (isset($ext['start_time'])) {
                        $v['start_time'] = $ext['start_time'];
                    }
                    if (isset($ext['end_time'])) {
                        $v['end_time'] = $ext['end_time'];
                    }
                    if (isset($ext['request_link'])) {
                        $v['request_link'] = $ext['request_link'];
                    }
                    if (isset($ext['order_link'])) {
                        $v['order_link'] = $ext['order_link'];
                        $order_task = DB::table('amazon_place_order_task')->where('id',$ext['order_id'])->select('platform_id')->first();
                        $spulist = DB::table('amazon_place_order_detail as a')->leftJoin('self_spu as b','a.spu_id','=','b.id')
                        ->where('order_id',$ext['order_id'])->select('b.spu','b.old_spu')->groupBy('a.spu_id')->get()->toArray();
                        if(!empty($spulist)){
                            foreach ($spulist as $sp){
                                $v['spulist'][] = $sp->old_spu ? $sp->old_spu : $sp->spu;
                            }
                        }
                        if(!empty($order_task)){
                            if($order_task->platform_id>0){
                                $platfromData = $baseModel->GetPlatform($order_task->platform_id);
                                if($platfromData){
                                    $v['platform_name'] = $platfromData['name'];
                                }
                            }
                        }
                    }
                    if (isset($ext['transfers_link'])) {
                        $v['transfers_link'] = $ext['transfers_link'];
                        $goods_transfers = DB::table('goods_transfers')->where('order_no',$ext['transfers_id'])->select('platform_id','type_detail')->first();
                        if(!empty($goods_transfers)){
                            if($goods_transfers->platform_id>0) {
                                $platfromData = $baseModel->GetPlatform($goods_transfers->platform_id);
                                if ($platfromData) {
                                    $v['platform_name'] = $platfromData['name'];
                                }
                                $v['type_name'] = $baseModel->GetFieldTypeDetailArr()[$goods_transfers->type_detail];
                            }
                        }
                    }
                    if (isset($ext['request_id'])) {
                        try {
                            //code...
                            if(array_key_exists($ext['request_id'],$request_detail)){
                                $v['sku_count'] = count($request_detail[$ext['request_id']]);
                                $v['request_id'] = $ext['request_id'];
                                $v['request_status'] = $request_detail[$ext['request_id']][0]['request_status'];
                                $shop_name = $baseModel->GetShop($request_detail[$ext['request_id']][0]['shop_id']);
                                //店铺名
                                if($shop_name){
                                    $v['shop_name'] = $shop_name['shop_name'];
                                }else{
                                    $v['shop_name'] = '';
                                }
                                $request_status = $baseModel->GetPlan($request_detail[$ext['request_id']][0]['request_status']);
                                //补货状态
                                if($request_status){
                                    $v['status_name'] = $request_status['status_name'];
                                }else{
                                    $v['status_name'] = '';
                                }
                                //快递方式
                                $v['transport_type'] = $request_detail[$ext['request_id']][0]['transportation_mode_name'] ?? '';
                            }else{
                                $v['sku_count'] = 0;
                                $v['status_name'] = '';
                                $v['shop_name'] = '';
                                $v['transport_type'] = '';
                            }

                        } catch (\Throwable $th) {
                            //throw $th;
                            $v['sku_count'] = 0;
                            $v['status_name'] = '';
                            $v['shop_name'] = '';
                            $v['transport_type'] = '';
                        }
                          
                
                        try {
                            //code...
                              //计划发货总计
                            if(array_key_exists($ext['request_id'],$all_num)){
                                $v['sum'] = array_sum($all_num[$ext['request_id']]);
                            }else{
                                $v['sum'] = 0;
                            }
                        } catch (\Throwable $th) {
                            //throw $th;
                            $v['sum'] = 0;
                        }
                       
                     
                    }
                    $feedback_content2 = json_decode($v['feedback_content2'],true);
                    if (isset($feedback_content2['tasks_ext'])) {
                        $v['tasks_text'] = $feedback_content2['tasks_text'];
                    }
                    if (isset($feedback_content2['tasks_img'])) {
                        $v['tasks_img'] = $feedback_content2['tasks_img'];
                    }
                    if (isset($feedback_content2['tasks_file'])) {
                        $v['tasks_file'] = $feedback_content2['tasks_file'];
                    }
                }

                if ($v['state'] == 2 && $v['time_end_yj'] < $time_now && $v['task_state'] != 2) {
                    //已逾期：状态 = 2、预计结束时间 < 当前时间
                    if (isset($v['request_status'])) {
                        if ($v['request_status'] > 3) {
                            $arr['overdue'][] = $v;
                        }
                    } else {
                        $arr['overdue'][] = $v;
                    }
                } else if ($v['state'] == 2 && $v['time_end_yj'] >= $time_now && $v['task_state'] != 2) {
                    //未逾期：状态 = 2、预计结束时间 >= 当前时间
                    if (isset($v['request_status'])) {
                        if ($v['request_status'] > 3) {
                            $arr['not_overdue'][] = $v;
                        }
                    } else {
                        $arr['not_overdue'][] = $v;
                    }
                } else if ($v['state'] == 4 && $v['task_state'] != 2) {
                    //已放弃：状态 = 4
                    $arr['abandon'][] = $v;
                } else if ($v['state'] == 3 && $v['task_state'] != 2) {
                    //已完成：状态 = 3
                    if (isset($v['request_status'])) {
                        if ($v['request_status'] > 3) {
                            $arr['complete'][] = $v;
                        }
                    } else {
                        $arr['complete'][] = $v;
                    }
                } else if ($v['state'] == 1 && $v['task_state'] != 2 && $v['node_state'] == 2) {
                    //未开始：状态 = 1
                    if (isset($v['request_status'])) {
                        if ($v['request_status'] > 3) {
                            $arr['not_start'][] = $v;
                        }
                    } else {
                        $arr['not_start'][] = $v;
                    }
                }
            }
        }
        return $arr;
    }

////////////////////// 任务列表

    /**
     * 任务定时器--数据
     * @param name 定时器名称
     * @param account_cj 创建人
     * @param task_name 循环任务
     * @param state 状态：1.未开始、2.运行中、3.暂停、4.结束
     * @param create_time 创建时间
     */
    public function task_timer($data)
    {
        $where = "1=1";

        //name 定时器名称
        if (isset($data['name'])) {
            $where .= " and tt.`name` like '%{$data['name']}%'";
        }
        //account_cj 创建人
        if (isset($data['account_cj'])) {
            $where .= " and u.`account` like '%{$data['account_cj']}%'";
        }
        //task_name 循环任务
        if (isset($data['task_name'])) {
            $where .= " and t.`name` like '%{$data['task_name']}%'";
        }
        //state 状态：1.未开始、2.运行中、3.暂停、4.结束
        if (isset($data['state'])) {
            $where .= " and tt.`state`={$data['state']}";
        }
        //create_time 创建时间
        if (!empty($data['create_time'])) {
            $state_time = $data['create_time'][0] . ' 00:00:00';
            $end_time = $data['create_time'][1] . ' 23:59:59';
            $where .= " and tt.create_time>='{$state_time}' and tt.create_time<='{$end_time}'";
        }
        //分页
        $limit = "";
        if ((!empty($data['page'])) and (!empty($data['page_count']))) {
            $limit = " limit " . ($data['page'] - 1) * $data['page_count'] . ",{$data['page_count']}";
        }

        $sql = "select SQL_CALC_FOUND_ROWS tt.*, u.account as account_cj, t.name as task_name
					from tasks_timer tt
					inner join users u on u.Id = tt.user_id
					inner join tasks t on t.Id = tt.task_id
					where {$where}
				    order by tt.Id desc {$limit}";
        $list = json_decode(json_encode(db::select($sql)), true);

        //// 总条数
        if (isset($data['page']) and isset($data['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }
        $return['list'] = $list;
        return $return;
    }

    /**
     * 新增任务定时器
     * @parma name 定时器名称
     * @param user_id 创建人
     * @param task_id 任务id
     * @param desc 描述
     * @param time_state 开始时间
     * @param time_end 结束时间
     * @param loop_type 循环类型：1.每天、2.每周、3.每月
     * @param loop_time 循环时间
     */
    public function task_timer_add($data)
    {
        //新增定时器，验证唯一
        // 验证唯一
        $sql = "select `Id`
					from `tasks_timer`
					where `name` = '{$data['name']}'";
        $timer_find = json_decode(json_encode(db::select($sql)), true);
        if (!empty($timer_find)) {
            return '定时器名称不能重复';
        }

        //// 新增任务
        $field_arr = array('name', 'user_id', 'task_id', 'desc', 'time_state', 'time_end', 'loop_type', 'loop_time');
        $data['loop_time'] = (!empty($data['loop_time'])) ? implode(',', $data['loop_time']) : '';
        $field = "create_time";
        $insert = "now()";
        foreach ($data as $k => $v) {
            if (in_array($k, $field_arr)) {
                $field .= ",`{$k}`";
                $insert .= ",'{$v}'";
            }
        }

        $sql = "insert ignore into tasks_timer({$field}) values ({$insert})";
        $add = db::insert($sql);
        if ($add) {
            return 1;
        } else {
            return '新增失败';
        }
    }

    /**
     * 编辑任务定时器
     * @param Id 任务任务定时器id
     */
    public function task_timer_update($data)
    {
        $set = "";
        if (!empty($data['loop_time'])) {
            $data['loop_time'] = implode(',', $data['loop_time']);
        }
        $field_arr = array('name', 'task_id', 'desc', 'time_state', 'time_end', 'loop_type', 'loop_time', 'state');
        foreach ($data as $k => $v) {
            if (in_array($k, $field_arr)) {
                // name 定时器名称
                if ($k == 'name') {
                    // 验证唯一
                    $sql = "select `Id`
								from `tasks_timer`
								where `Id`!={$data['Id']} and `name`='{$data['name']}'";
                    $timer_find = json_decode(json_encode(db::select($sql)), true);
                    if (!empty($timer_find)) {
                        return '定时器名称不能重复';
                    }
                }
                $set .= ",`{$k}`='{$v}'";
            }
        }
        if (empty($set)) {
            return '修改数据为空';
        }
        $set = substr($set, 1);

        $sql = "update tasks_timer
					set {$set}
					where `Id` = {$data['Id']}";
        $update = db::update($sql);
        if ($update !== false) {
            return 1;
        } else {
            return '编辑失败';
        }
    }

    /**
     * 删除任务定时器
     * @param Id 任务定时器id
     */
    public function task_timer_del($data)
    {
        $sql = "delete
					from tasks_timer
					where `Id`={$data['Id']}";
        $del = db::delete($sql);
        if ($del) {
            return 1;
        } else {
            return '删除失败';
        }
    }


    /**
     * 触发定时器
     */
    public function timer_trigger()
    {
        ////获取定时器（1.未开始、2.运行中、3.暂停）
        $sql = "select *
					from `tasks_timer`
					where `state` != 4";
        $timer_list = json_decode(json_encode(db::select($sql)), true);
        if (empty($timer_list)) {
            return 1;
        }

        // 时间  strtotime("2020-10-1")
        $time = time();
        $time_now = date('Y-m-d', $time);//当天时间
        $week = date("w", $time);//星期几
        $day = date("j", $time);//几号

        //开启事务
        db::beginTransaction();

        //// 修改状态、创建任务
        foreach ($timer_list as $k => $v) {

            $set = '';
            $is_add = 0;

            if ($v['state'] == 1 && $time_now >= $v['time_state']) {
                // 未开始  --》 运行中：修改状态、新增任务
                $set .= "`state`=2";

                if ($v['loop_type'] == 1) {
                    //每天
                    $is_add = 1;
                } else if ($v['loop_type'] == 2) {
                    //每周
                    $loop_time = explode(",", $v['loop_time']);
                    if (in_array($week, $loop_time)) {
                        $is_add = 1;
                    }
                } else if ($v['loop_type'] == 3) {
                    //每月
                    $loop_time = explode(",", $v['loop_time']);
                    if (in_array($day, $loop_time)) {
                        $is_add = 1;
                    }
                }
            } else if (($v['state'] == 2 || $v['state'] == 3) && $v['time_end'] != '0000-00-00' && $time_now > $v['time_end']) {
                // 运行中  --》 结束：修改状态
                $set .= "`state`=4";
            } else if ($v['state'] == 2 && $time_now >= $v['time_state'] && ($time_now <= $v['time_end'] || $v['time_end'] == '0000-00-00')) {
                // 继续运行：新增任务
                if ($v['loop_type'] == 1) {
                    //每天
                    $is_add = 1;
                } else if ($v['loop_type'] == 2) {
                    //每周
                    $loop_time = explode(",", $v['loop_time']);
                    if (in_array($week, $loop_time)) {
                        $is_add = 1;
                    }
                } else if ($v['loop_type'] == 3) {
                    //每月
                    $loop_time = explode(",", $v['loop_time']);
                    if (in_array($day, $loop_time)) {
                        $is_add = 1;
                    }
                }
            }

            //// 修改状态
            if (!empty($set)) {
                $sql = "update tasks_timer
							set {$set}
							where `Id` = {$v['Id']}";
                $timer_update = db::update($sql);
                if (!$timer_update) {
                    db::rollback();// 回调
                }
            }

            //// 创建任务
            if ($is_add == 1) {
                //获取任务详情
                $arr = array();
                $arr['task_id'] = $v['task_id'];
                $task_info = $this->task_info($arr);
                //  处理数据
                // 名称
                $task_info['basic']['name'] = $task_info['basic']['name'] . '_' . date('YmdHis', time());
                // 审核人
//				var_dump(empty($task_info['basic']['examine']));exit;
                if (!empty($task_info['basic']['examine'])) {
                    $examine = array();
                    foreach ($task_info['basic']['examine'] as $k => $v) {
                        $examine[] = $v['user_id'];
                    }
                    $task_info['basic']['examine'] = $examine;
                }
                // 抄送人
                if (!empty($task_info['basic']['user_cs'])) {
                    $task_info['basic']['user_cs'] = explode(",", $task_info['basic']['user_cs']);
                }
                // 调用接口新增
                $arr = $task_info['basic'];
                $arr['node'] = $task_info['node'];
                $task_add = $this->task_add($arr);
                if ($task_add != 1) {
                    db::rollback();// 回调
                }
            }

            db::commit();// 确认
        }

        return 1;
    }


    /**
     * 关联选择模板查找
     */
    public function choice_template($data)
    {
        $list = Db::table('task_class')->where('id', $data['class_id'])->pluck('task_id');
        return $list;
    }

    /**
     * 删除未发布任务的补货计划
     */
    public function delete_replenishment_data($data)
    {
        $user_id = $data['user_info']['Id'];
        $del = Db::table('amazon_buhuo_request')->where(['request_userid' => $user_id, 'request_status' => 2])->where('id', '!=', $data['request_id'])->delete();
        if ($del !== false) {
            return 1;
        } else {
            return 2;
        }

    }

    /**
     * 接受任务开始执行
     */
    public function task_accept_model($data)
    {
        $Id = $data['Id'];
        $node_id = $data['tasks_node_id'];
        $task_id = $data['task_id'];
        if(isset($data['user_id'])){
            $user_id = $data['user_id'];
        }else{
            $token = $data['token'];
            //根据token识别申请人
            $user_data = DB::table('users')->where('token', '=', $token)->select('Id', 'account')->first();
            $user_id = $user_data->Id;
        }


        //当前时间
        $time = time();
        $time_now = date('Y-m-d H:i:s', $time);
        $node = DB::table('tasks_node')->where('task_id', $task_id)->select('Id', 'state')->get();
        if (!empty($node)) {
            $task = DB::table('tasks')->where('Id', $task_id)->select('state', 'class_id', 'ext')->first();
            if (!empty($task)) {
                if ($task->class_id == 3 || $task->class_id == 4 || $task->class_id == 2|| $task->class_id == 124) {
                    $ext = json_decode($task->ext, true);
                    $request = DB::table('amazon_buhuo_request')->where('Id', $ext['request_id'])->select('Id', 'request_status')->first();
                    if (!empty($request)) {
                        if ($request->request_status < 4) {
                            return ['type' => 'fail', 'msg' => ['data' => '未审核通过,无法接受任务']];
                        } else {
                            $request_link = '/amazon_buhuo_data?id=' . $request->Id;
                        }
                    } else {
                        return ['type' => 'fail', 'msg' => ['data' => '没有此计划']];
                    }
                } else {
                    if ($task->state != 3) {
                        return ['type' => 'fail', 'msg' => ['data' => '当前状态暂时无法接受任务']];
                    }
                }
            } else {
                return ['type' => 'fail', 'msg' => ['data' => '没有此任务，请确认是否已被删除']];
            }
            //开启事务
            db::beginTransaction();
            if (count($node) > 1) {
//                $update = Db::table('tasks_node')->where(['Id' => $node_id,'state' => 1])->update(['state'=>2,'time_state'=>$time_now]);
//                if(!$update){
//                    db::rollback();// 回调
//                    return ['type'=>'fail','msg'=>['data'=>'接受任务失败']];
//                }
//            }else{
                $nodeId = array();
                foreach ($node as $k => $nodeVal) {
                    $nodeId[$k] = $nodeVal->Id;
                }
                $node_key = array_search($node_id, $nodeId);
                if ($node_key != 0) {
                    $last_id = $nodeId[$node_key - 1];
                    $last_node = DB::table('tasks_node')->where('Id', $last_id)->select('state')->first();
                    if ($last_node->state != 3) {
                        db::rollback();// 回调
                        return ['type' => 'fail', 'msg' => ['data' => '接受任务失败，上一个任务还未完成']];
                    }
//                    else{
//                        $update = Db::table('tasks_node')->where(['Id' => $node_id,'state' => 1])->update(['state'=>2,'time_state'=>$time_now]);
//                        if(!$update){
//                            db::rollback();// 回调
//                            return ['type'=>'fail','msg'=>['data'=>'接受任务失败']];
//                        }
//                    }
                }
            }
            //获取节点任务
            $sql = "select *
					from tasks_son
					where `Id`={$Id}";
            $tasks_son_list = json_decode(json_encode(db::select($sql)), true);
            //任务开启
            $bb = $time + (3600 * 24 * $tasks_son_list[0]['day_yj']);
            $time_end_yj = date('Y-m-d H:i:s', $bb);
            $sql = "update tasks_son
						set state=2, time_state='{$time_now}', time_end_yj='{$time_end_yj}'
						where `Id` ={$Id}";
            $tasks_son_update = db::update($sql);
            if (!$tasks_son_update) {
                db::rollback();// 回调
                return ['type' => 'fail', 'msg' => ['data' => '接受任务失败']];
            }
            db::commit();
            if (isset($request_link)) {
                return ['type' => 'success', 'msg' => ['data' => '接受任务成功', 'link' => $request_link]];
            } else {
                return ['type' => 'success', 'msg' => ['data' => '接受任务成功']];
            }

        } else {
            return ['type' => 'fail', 'msg' => ['data' => '接受任务失败,没有节点']];
        }
    }

    /**
     * 修改进度说明
     */
//    public function text_update($data)
//    {
//        $task_id = isset($data['task_id']) ? $data['task_id'] : 0;
//        $class_id = isset($data['class_id']) ? $data['task_id'] : 0;
//        $task_text = isset($data['task_text']) ? $data['task_text'] : '';
//        $task_img = isset($_FILES['img']) ? $_FILES['img'] : '';
//        $task_file = isset($_FILES['files']) ? $_FILES['files'] : '';
//        $img_url = array();
//        $file_url = array();
//        if ($task_img != '') {
//            $img_count = count($task_img['name']);
//            for ($i = 0; $i < $img_count; $i++) {
//                $img_name = $task_img['name'][$i];
//                $img_name = substr($img_name, strrpos($task_img['name'][$i], "."));
//                $img = time() . $i . $img_name;
//                $tmp_img = $task_img['tmp_name'][$i];
//                $error = $task_img['error'][$i];
//                if ($error == 0) {
//                    $save = move_uploaded_file($tmp_img, $_SERVER['DOCUMENT_ROOT'] . '/task_img/' . $img);
//                    if ($save) {
//                        $img_url[$i] = '/task_img/' . $img;
//                    } else {
//                        return ['type' => 'fail', 'msg' => '图片上传失败'];
//                    }
//                }
//            }
//        }
//        if ($task_file != '') {
//            $file_count = count($task_file['name']);
//            for ($i = 0; $i < $file_count; $i++) {
//                $file_name = $task_file['name'][$i];
//                $tmp_file = $task_file['tmp_name'][$i];
//                $error = $task_file['error'][$i];
//                if ($error == 0) {
//                    $save = move_uploaded_file($tmp_file, $_SERVER['DOCUMENT_ROOT'] . '/task_img/' . $file_name);
//                    if ($save) {
//                        $file_url[$i] = '/task_img/' . $file_name;
//                    } else {
//                        return ['type' => 'fail', 'msg' => '文件上传失败'];
//                    }
//                }
//            }
//        }
//        if ($task_id != 0) {
//            $task_data = DB::table('tasks')->where('Id', $task_id)->select('ext')->first();
//            if (!empty($task_data)) {
//                $ext = json_decode($task_data->ext, true);
//                if (array_key_exists('tasks_text', $ext)) $ext['tasks_text'] = $task_text;
//                if (array_key_exists('tasks_img', $ext)) {
//                    if (!empty($img_url)) {
//                        $ext['tasks_img'] = $img_url;
//                    } else {
//                        $ext['tasks_img'] = $ext['tasks_img'];
//                    }
//                }
//                if (array_key_exists('tasks_file', $ext)) {
//                    if (!empty($file_url)) {
//                        $ext['tasks_file'] = $file_url;
//                    } else {
//                        $ext['tasks_file'] = $ext['tasks_file'];
//                    }
//                }
//                $ext = json_encode($ext);
//                $task_update = DB::table('tasks')->where('Id', $task_id)->update(['ext' => $ext]);
//                return ['type' => 'success', 'msg' => '反馈成功'];
//            } else {
//                return ['type' => 'fail', 'msg' => '没有此任务，请查看是否被删除'];
//            }
//        } else {
//            return ['type' => 'fail', 'msg' => 'task_id为空'];
//        }
//    }

    //任务中反馈
    public function  task_feedback($data){
        $task_son_id = isset($data['task_son_id']) ? $data['task_son_id'] : 0;
        $task_text = isset($data['task_text']) ? $data['task_text'] : null;
        $task_img = isset($_FILES['img']) ? $_FILES['img'] : null;
        $task_file = isset($_FILES['files']) ? $_FILES['files'] : null;
        $feedback_content2 = DB::table('tasks_son')->where('Id',$task_son_id)->select('feedback_content2')->first();
        if(!empty($feedback_content2->feedback_content2)){
            $content = json_decode($feedback_content2->feedback_content2,true);
        }
        if (!empty($task_img)) {
            $img_count = count($task_img['name']);
            for ($i = 0; $i < $img_count; $i++) {
                $img_name = $task_img['name'][$i];
                $img_name = substr($img_name, strrpos($task_img['name'][$i], "."));
                $img = time() . $i . $img_name;
                $tmp_img = $task_img['tmp_name'][$i];
                $error = $task_img['error'][$i];
                if ($error == 0) {
                    $save = move_uploaded_file($tmp_img, $_SERVER['DOCUMENT_ROOT'] . '/task_img/' . $img);
                    if ($save) {
                        $img_url[$i] = '/task_img/' . $img;
                    } else {
                        return ['type' => 'fail', 'msg' => '图片上传失败'];
                    }
                }
            }
        }else{
            if(isset($content['tasks_img'])){
                $img_url = $content['tasks_img'];
            }
        }
        if (!empty($task_file)) {
            $file_count = count($task_file['name']);
            for ($i = 0; $i < $file_count; $i++) {
                $file_name = $task_file['name'][$i];
                $tmp_file = $task_file['tmp_name'][$i];
                $error = $task_file['error'][$i];
                if ($error == 0) {
                    $save = move_uploaded_file($tmp_file, $_SERVER['DOCUMENT_ROOT'] . '/task_img/' . $file_name);
                    if ($save) {
                        $file_url[$i] = '/task_img/' . $file_name;
                    } else {
                        return ['type' => 'fail', 'msg' => '文件上传失败'];
                    }
                }
            }
        }else{
            if(isset($content['tasks_file'])){
                $file_url = $content['tasks_file'];
            }
        }
        if ($task_son_id != 0) {
            $arr = array();
            if(!empty($task_text)) {
                $arr['tasks_text'] = $task_text;
            }
            if (!empty($img_url)) {
                $arr['tasks_img'] = $img_url;
            }
            if (!empty($file_url)) {
                $arr['tasks_file'] = $file_url;
            }
            $arr = json_encode($arr);
            $task_update = DB::table('tasks_son')->where('Id', $task_son_id)->update(['feedback_content2' => $arr]);
            return ['type' => 'success', 'msg' => '反馈成功'];
        } else {
            return ['type' => 'fail', 'msg' => 'task_id为空'];
        }
    }

    //修改任务中反馈
    public function  feedback_update($data){
        $task_son_id = isset($data['task_son_id']) ? $data['task_son_id'] : 0;
        $task_text = isset($data['task_text']) ? $data['task_text'] : null;
        $task_img = isset($_FILES['img']) ? $_FILES['img'] : null;
        $task_file = isset($_FILES['files']) ? $_FILES['files'] : null;
        if ($task_img != '') {
            $img_count = count($task_img['name']);
            for ($i = 0; $i < $img_count; $i++) {
                $img_name = $task_img['name'][$i];
                $img_name = substr($img_name, strrpos($task_img['name'][$i], "."));
                $img = time() . $i . $img_name;
                $tmp_img = $task_img['tmp_name'][$i];
                $error = $task_img['error'][$i];
                if ($error == 0) {
                    $save = move_uploaded_file($tmp_img, $_SERVER['DOCUMENT_ROOT'] . '/task_img/' . $img);
                    if ($save) {
                        $img_url[$i] = '/task_img/' . $img;
                    } else {
                        return ['type' => 'fail', 'msg' => '图片上传失败'];
                    }
                }
            }
        }
        if ($task_file != '') {
            $file_count = count($task_file['name']);
            for ($i = 0; $i < $file_count; $i++) {
                $file_name = $task_file['name'][$i];
                $tmp_file = $task_file['tmp_name'][$i];
                $error = $task_file['error'][$i];
                if ($error == 0) {
                    $save = move_uploaded_file($tmp_file, $_SERVER['DOCUMENT_ROOT'] . '/task_img/' . $file_name);
                    if ($save) {
                        $file_url[$i] = '/task_img/' . $file_name;
                    } else {
                        return ['type' => 'fail', 'msg' => '文件上传失败'];
                    }
                }
            }
        }
        if ($task_son_id != 0) {
            $arr = array();
            if(!empty($task_text)) {
                $arr['tasks_text'] = $task_text;
            }
            if (!empty($img_url)) {
                $arr['tasks_img'] = $img_url;
            }
            if (!empty($file_url)) {
                $arr['tasks_file'] = $file_url;
            }
            $arr = json_encode($arr);
            $task_update = DB::table('tasks_son')->where('Id', $task_son_id)->update(['feedback_content2' => $arr]);
            return ['type' => 'success', 'msg' => '反馈成功'];
        } else {
            return ['type' => 'fail', 'msg' => 'task_id为空'];
        }
    }


    /**
     * 任务评分
     */
    public function user_cj_score($data)
    {
        $score = isset($data['score']) ? $data['score'] : 0;
        $task_id = isset($data['task_id']) ? $data['task_id'] : 0;
        $user_cj = isset($data['user_cj']) ? $data['user_cj'] : 0;
        $user_fz = isset($data['user_fz']) ? $data['user_fz'] : 0;
        $state = isset($data['state']) ? $data['state'] : 0;
        if ($score != 0) {
            if ($state < 4) {
                return ['type' => 'fail', 'msg' => '任务未完成无法验收'];
            }
            if ($state > 4) {
                return ['type' => 'fail', 'msg' => '此任务已验收过'];
            }
            db::beginTransaction();
            $task_update = DB::table('tasks')->where('Id', $task_id)->where('user_cj', $user_cj)->update(['score' => $score, 'state' => 5]);
            if ($task_update) {
                if (!empty($data['content'])) {
                    // 新增任务消息
                    $now = date('Y-m-d H:i:s');
                    $insert_msg = DB::table('tasks_news')->insert(['task_id' => $task_id, 'user_fs' => $user_cj, 'user_js' => $user_fz, 'type' => 1, 'content' => $data['content'], 'create_time' => $now]);
                    if (!$insert_msg) {
                        db::rollback();// 回调
                        return ['type' => 'fail', 'msg' => '验收失败，tasks_news表错误'];
                    }
                }
                $select_sql = "select class_id,ext,name
                        from tasks
		                where `Id` = {$data['task_id']}";
                $select = db::select($select_sql);
                if (!empty($select)) {
                    // 如有接收人，给接收人发送站内消息
                    if (!empty($user_fz) && isset($insert_msg)) {
                        $content = "任务：{$select[0]->name}，有发送给您的消息！";
                        $tiding = DB::table('tidings')->insertGetId(
                            ["user_fs" => $user_cj, "user_js" => $user_fz, "title" => '任务评论', "content" => $content, "object_id" => $task_id, "object_type" => 1, "type" => 1, "create_time" => now()]
                        );
                        if ($tiding) {
                            $this->redis_tiding($tiding, 0, $user_fz, '任务评论', $content, $data['task_id'], 1, 1);
                        }
                    }
                    if ($select[0]->class_id == 3 || $select[0]->class_id == 4) {
                        $ext = json_decode($select[0]->ext, true);
                        $request_id = $ext['request_id'];
                        $update_sql = "update amazon_buhuo_request
		            set `request_status`=10
		            where `id` = {$request_id}";
                        $update_status = db::update($update_sql);
                        if (!$update_status) {
                            db::rollback();// 回调
                            return ['type' => 'fail', 'msg' => '验收失败,amazon_buhuo_request表错误'];
                        }
                    }
                }

                db::commit();
                return ['type' => 'success', 'msg' => '验收成功'];
            } else {
                db::rollback();// 回调
                return ['type' => 'fail', 'msg' => '验收失败,tasks表错误'];
            }
        } else {
            return ['type' => 'fail', 'msg' => '请至少选择一颗星'];
        }
    }


    /**
     * 任务数据统计
     */
    public function task_lib_data($data)
    {
        $where = 'a.state=1';
        if (!empty($data['organize_id'])) {
            $where .= " and b.organize_id={$data['organize_id']}";
        }
        if (!empty($data['user_id'])) {
            $where .= " and a.Id={$data['user_id']}";
        }
//        if(!empty($data['class_id'])){
//            $where .=" and b.organizes_id={$data['organize_id']}";
//        }
        $sql = "SELECT a.Id,a.account,c.name
                FROM
                    users a
                LEFT JOIN organizes_member b ON a.Id = b.user_id
                LEFT JOIN organizes c ON b.organize_id = c.Id
                WHERE
                    $where
                ORDER BY
                    a.Id asc";
        $user_data = DB::select($sql);
        if (!empty($user_data)) {
            foreach ($user_data as $k => $userVal) {
                $taskIds = [];
                $is_check = 0;
                if (isset($data['tasks_start_time'])){
                    $is_check = 1;
                    $taskSon = $this->taskSonModel::query()
                        ->whereBetween('time_state', $data['tasks_start_time'])
                        ->where('user_id', $userVal->Id)
                        ->select('task_id')
                        ->get();
                    if ($taskSon->isNotEmpty()){
                        $taskIds = array_column($taskSon->toArray(), 'task_id');
                    }
                }
                if (isset($data['tasks_end_time'])){
                    $is_check = 1;
                    $taskSon = $this->taskSonModel::query()
                        ->whereBetween('time_end_sj', $data['tasks_end_time'])
                        ->where('user_id', $userVal->Id)
                        ->select('task_id')
                        ->get();
                    if ($taskSon->isNotEmpty()){
                        $taskIds = array_column($taskSon->toArray(), 'task_id');
                    }
                }
                //已发布任务数量
                $tasks = $this->task_cj_num($userVal->Id, $taskIds, $is_check);
                $user_data[$k]->task_cj = count($tasks);
                //已审核任务数量
                $user_data[$k]->task_has_audit = $this->task_audit_num($userVal->Id, 'hasAudit', $taskIds, $is_check);
                //待审核任务数量
                $user_data[$k]->task_no_audit = $this->task_audit_num($userVal->Id, 'noAudit', $taskIds, $is_check);
                //未开始任务数量
                $user_data[$k]->task_nostart = $this->task_son_num($userVal->Id, 1, $taskIds, $is_check);
                //进行中任务数量
                $user_data[$k]->task_ongoing = $this->task_son_num($userVal->Id, 2, $taskIds, $is_check);
                //已完成任务数量
                $user_data[$k]->task_hasover = $this->task_son_num($userVal->Id, 3, $taskIds, $is_check);
                //已放弃任务数量
                $user_data[$k]->task_giveup = $this->task_son_num($userVal->Id, 4, $taskIds, $is_check);
                //已验收任务数量
                $user_data[$k]->task_acceptance = $this->task_acceptance_num($userVal->Id, $taskIds, $is_check);
                $time = $this->task_time($userVal->Id, $taskIds, $is_check);
                //平均任务接受时长
                $user_data[$k]->task_avg_accept = $time['accept'] > 0 ? $time['accept'] : null;
                //平均任务完成时长
                $user_data[$k]->task_avg_complete = $time['complete'] > 0 ? $time['complete'] : null;
                //平均任务审核时长
                $user_data[$k]->task_avg_audit = $this->task_audit_time($userVal->Id, $taskIds, $is_check) > 0 ? $this->task_audit_time($userVal->Id, $taskIds, $is_check) : null;
                //平均任务得分
                $user_data[$k]->task_avg_score = $this->task_avg_score($userVal->Id, $taskIds, $is_check);
            }
        }

        return $user_data;
    }

    /**
     * 已发布的任务数量
     */
    public function task_cj_num($user, $taskIds, $is_check)
    {
        $count = null;

        $data = DB::table('tasks')->where('user_cj', $user);
        if ($is_check){
            $data = $data->whereIn('Id', $taskIds);
        }
        $data = $data->select('Id')->get()->toArray();

        return $data;
    }

    /**
     * 已审核,待审核任务数量
     */
    public function task_audit_num($user, $type, $taskIds, $is_check)
    {
        $count = null;
        $array = array();
        if ($type == 'hasAudit') $array = [3, 4];
        if ($type == 'noAudit') $array = [1, 2];
        $data = DB::table('tasks_examine')->where('user_id', $user)->whereIn('state', $array);
        if ($is_check){
            $data = $data->whereIn('task_id', $taskIds);
        }
        $data = $data->select('Id')->get();
        if (!$data->isEmpty()) $count = count($data);

        return $count;
    }

    /**
     * 已验收的任务数量
     */
    public function task_acceptance_num($user, $taskIds, $is_check)
    {
        $count = null;

        $data = DB::table('tasks')->where('user_cj', $user)->where('score', '!=', 0);
        if ($is_check){
            $data = $data->whereIn('Id', $taskIds);
        }
        $data = $data->select('Id')->get();
        if (!$data->isEmpty()) $count = count($data);

        return $count;
    }

    /**
     * 1.未开始、2.进行中、3.已完成、4.已放弃的任务
     */
    public function task_son_num($user, $state, $taskIds, $is_check)
    {
        $count = null;

        $data = DB::table('tasks_son')->where('user_id', $user)->where('state', $state);

        if ($is_check){
            $data = $data->whereIn('task_id', $taskIds);
        }
        $data = $data->select('Id')->get();
        if (!$data->isEmpty()) $count = count($data);

        return $count;
    }

    /**
     * 平均任务接受，完成时长
     */
    public function task_time($user, $taskIds, $is_check)
    {
        $data = DB::table('tasks_son')->where('user_id', $user)->where('task_id', '>', '330')->whereIn('state', [2, 3]);
        if ($is_check){
            $data = $data->whereIn('task_id', $taskIds);
        }
        $data = $data->select('Id', 'state', 'task_id', 'tasks_node_id', 'create_time', 'time_state', 'time_end_sj')->get();
        $time = array('accept' => 0, 'complete' => 0);

        if (!$data->isEmpty()) {
            $accept_count = 0;
            $complete_count = 0;
            $accept_time = [];
            $complete_time = [];
            foreach ($data as $val) {
                $last_id = 1;
                if ($val->Id > 1) $last_id = $val->Id - 1;
                $last_task_son = DB::table('tasks_son')->where('Id', $last_id)->where('task_id', $val->task_id)->select('task_id', 'tasks_node_id', 'create_time', 'time_state', 'time_end_sj')->first();
                if (!empty($last_task_son)) {
                    if ($last_task_son->tasks_node_id != $val->tasks_node_id) {
                        $accept_time[] = strtotime($val->time_state) - strtotime($last_task_son->time_end_sj);
                    } else {
                        $accept_time[] = strtotime($val->time_state) - strtotime($val->create_time);
                    }
                } else {
                    $accept_time[] = strtotime($val->time_state) - strtotime($val->create_time);
                }
                $accept_count++;
                if ($val->state == 3) {
                    $complete_time[] = strtotime($val->time_end_sj) - strtotime($val->time_state);
                    $complete_count++;
                }
            }
            $accept_time_sum = array_sum($accept_time);
            $complete_time_sum = array_sum($complete_time);
            //平均接受时长
            $time['accept'] = $accept_count > 0 ? round($accept_time_sum / ($accept_count * 60), 2) : null;
            //平均完成时长
            $time['complete'] = $complete_count > 0 ? round($complete_time_sum / ($complete_count * 60), 2) : null;
        }


        return $time;
    }

    /**
     * 平均任务审核时长
     */
    public function task_audit_time($user, $taskIds, $is_check)
    {
        $data = DB::table('tasks as a')
            ->leftJoin('tasks_examine as b', 'a.Id', '=', 'b.task_id')
            ->where('b.user_id', $user)
            ->where('a.Id', '>', '330')
            ->whereIn('b.state', [2, 3]);
        if ($is_check){
            $data = $data->whereIn('a.Id', $taskIds);
        }
        $data = $data->select('a.create_time', 'b.time_sh')
            ->get();
        $time = 0;
        if (!$data->isEmpty()) {
            $count = count($data);
            $create_time_sum = 0;
            $time_sh_sum = 0;
            foreach ($data as $val) {
                $create_time_sum += strtotime($val->create_time);
                $time_sh_sum += strtotime($val->time_sh);
            }
            //平均审核时长
            $time = round(($time_sh_sum - $create_time_sum) / ($count * 60), 2);
        }
        return $time;
    }

    /**
     * 平均任务得分
     */
    public function task_avg_score($user, $taskIds, $is_check)
    {
        $score = null;

        $data = DB::table('tasks')->where('user_fz', $user)->where('Id', '>', '330')->where('score', '!=', 0);
        if ($is_check){
            $data = $data->whereIn('Id', $taskIds);
        }
        $data = $data->select('Id', 'score')->get();
        if (!$data->isEmpty()) {
            $count = count($data);
            $score_sum = 0;
            foreach ($data as $val) {
                $score_sum += $val->score;
            }
            $score = round($score_sum / $count, 2);
        }

        return $score;
    }

    /**
     * 任务是否需要总经办介入
     * 1.是 2.否
     */
    public function general_office_intervened($data)
    {
        $is_intervention = $data['is_intervention'];
        $has_chose = $data['has_chose'];
        if ($is_intervention == 1) {
            $user = DB::table('organizes_member')->where('organize_id', 1)->select('user_id')->get();
            $users = json_decode(json_encode($user), true);
            $users = array_column($users, 'user_id');
            if (!empty($has_chose)) $users = array_merge($users, $has_chose);
        }
        if ($is_intervention == 2) {
            if (!empty($has_chose)) {
                $member = DB::table('organizes_member')->where('organize_id', 1)->select('user_id')->get();
                $members = json_decode(json_encode($member), true);
                $members = array_column($members, 'user_id');
                foreach ($has_chose as $key => $val) {
                    if (in_array($val, $members)) {
                        unset($has_chose[$key]);
                    }
                }
            }
            $users = array_values($has_chose);
        }
        $users = array_unique($users);
        return $users;
    }


    /**
     * 亚马逊站内活动任务字段接口
     * @param $data
     * @return mixed
     * type(1.活动类型 2.是否锁库存 3.调拨 4.自发货SKU是否关闭 5.叠加coupon 6.是否折扣重叠 7.店铺)
     */
    public function activity_api($data)
    {
        $return = array();
        if ($data['type'] == 1) {
            //活动类型
            $return = [
                ['id' => 0, 'activity_name' => '社交媒体促销'],
                ['id' => 1, 'activity_name' => '购买折扣'],
                ['id' => 2, 'activity_name' => '买一赠一'],
                ['id' => 3, 'activity_name' => '秒杀'],
                ['id' => 4, 'activity_name' => 'prime专享折扣'],
                ['id' => 5, 'activity_name' => 'sale price降价']
            ];
           // $return['list'] = $list;

        }elseif($data['type']==2){
            //是否锁库存
            $return = [
                ['id' => 0, 'lock_inventory' => '有锁库存'],
                ['id' => 1, 'lock_inventory' => '未锁库存']
            ];
        }elseif($data['type']==3){
            //调拨
            $return = [
                ['id' => 0, 'allocation' => '有调拨'],
                ['id' => 1, 'allocation' => '无调拨']
            ];
        }elseif($data['type']==4){
            //自发货SKU是否关闭
            $return = [
                ['id' => 0, 'self_close' => '已关闭'],
                ['id' => 1, 'self_close' => '未关闭']
            ];
        }elseif($data['type']==5){
            //叠加coupon
            $return = [
                ['id' => 0, 'coupon_name' => '不叠加'],
                ['id' => 1, 'coupon_name' => '最多5%，限制每个买家只能兑换一次'],
                ['id' => 2, 'coupon_name' => '大额coupon（超过20%）']
            ];
        }elseif($data['type']==6){
            //是否折扣重叠
            $return = [
                ['id' => 0, 'overlap' => '有重叠'],
                ['id' => 1, 'overlap' => '无重叠']
            ];
        }elseif($data['type']==7){
            //店铺
            $return = Db::table('shop')->select('Id','shop_name')->where('platform_id',5)->where('state','!=', 2)->get()->toArray();
        }
        return $return;

    }


    /**
     * 亚马逊站内活动任务字段接口
     * @param $data
     * @return mixed
     * type(1.活动类型 2.是否锁库存 3.调拨 4.自发货SKU是否关闭 5.叠加coupon 6.是否折扣重叠 7.店铺)
     */
    public function activity_outside_api($data)
    {
        $return = array();
        if ($data['type'] == 1) {
            //活动类型
            $return = [
                ['id' => 0, 'activity_name' => 'FB code'],
                ['id' => 1, 'activity_name' => '红人code'],
                ['id' => 2, 'activity_name' => '线下清库存']
            ];
           // $return['list'] = $list;

        }elseif($data['type']==2){
            //是否锁库存
            $return = [
                ['id' => 0, 'lock_inventory' => '有锁库存'],
                ['id' => 1, 'lock_inventory' => '未锁库存']
            ];
        }elseif($data['type']==3){
            //调拨
            $return = [
                ['id' => 0, 'allocation' => '有调拨'],
                ['id' => 1, 'allocation' => '无调拨']
            ];
        }elseif($data['type']==4){
            //自发货SKU是否关闭
            $return = [
                ['id' => 0, 'self_close' => '已关闭'],
                ['id' => 1, 'self_close' => '未关闭']
            ];
        }elseif($data['type']==5){
            //叠加coupon
            $return = [
                ['id' => 0, 'coupon_name' => '不叠加'],
                ['id' => 1, 'coupon_name' => '最多5%，限制每个买家只能兑换一次'],
                ['id' => 2, 'coupon_name' => '大额coupon（超过20%）']
            ];
        }elseif($data['type']==6){
            //是否折扣重叠
            $return = [
                ['id' => 0, 'overlap' => '有重叠'],
                ['id' => 1, 'overlap' => '无重叠']
            ];
        }elseif($data['type']==7){
            //店铺
            $return = Db::table('shop')->select('Id','shop_name')->where('platform_id',5)->where('state','!=', 2)->get()->toArray();
        }
        return $return;

    }


    /**
     * 生产下单是否新品选择接口
     * @param $data
     * @return mixed
     * 1.是 2.否
     */
    public function is_new_api($data){
        $return = array();
        $return = [
            ['id' => 1, 'is_new' => '是'],
            ['id' => 2, 'is_new' => '否']
        ];
        return  $return;
    }

//    public function getTastStatistics($params)
//    {
//        $list = db::table('tasks as a')
//            ->join('users as b', 'a.user_fz', '=', 'b.Id')
//            ->leftJoin('users as c', 'a.user_cj', '=', 'c.Id')
//            ->where('a.is_deleted', 0);
//        if (!$params['list_all']) {
//            if ($params['type'] == '1') {
//                // 任务
//                $list = $list
//                    ->where('a.user_fz', $params['user_info']['Id'])
//                    ->orWhere('a.user_cj', $params['user_info']['Id']);
//            } else if ($params['type'] == '2') {
//                // 任务模板
//                $list = $list->where('a.user_cj', $params['user_info']['Id']);
//            }
//        }
//
//        //name 任务名称
//        if (isset($params['name'])) {
//            $list = $list->where('a.name', 'like', '%'.$params['name'].'%');
//        }
//        //user_fz_name 负责人名称
//        if (isset($params['user_fz_name'])) {
//            $userMdl = db::table('users')
//                ->where('account', 'like', '%'.$params['user_fz_name'].'%')
//                ->get()
//                ->toArrayList();
//            $userIds = array_column($userMdl, 'Id');
//            $list = $list->whereIn('a.user_fz', $userIds);
//        }
//        //task_keys 任务关键字
//        if (isset($params['task_keys'])) {
//            $list = $list->where('a.ext', 'like', '%'.$params['task_keys'].'%');
//        }
//        //user_cj_name 创建人名称
//        if (isset($data['user_cj_name'])) {
//            $userMdl = db::table('users')
//                ->where('account', 'like', '%'.$params['user_cj_name'].'%')
//                ->get()
//                ->toArrayList();
//            $userIds = array_column($userMdl, 'Id');
//            $list = $list->whereIn('a.user_cj', $userIds);
//        }
//        //state 状态：1.待审核、2.已拒绝、3.进行中、4.待验收、5.已结束
//        if (isset($data['state'])) {
//            $list = $list->where('a.state', $params['state']);
//        }
//        //type 类型：1.任务、2.任务模板
//        if (isset($data['type'])) {
//            $list = $list->where('a.type', $params['type']);
//        }
//        //type_mb 模板类型：1.财务模板、2.人事模板、3.产品开发
//        if (!empty($data['type_mb'])) {
//            $list = $list->where('a.type_mb', $params['type_mb']);
//        }
//        //class_id 任务分类
//        if (isset($data['class_id'])) {
//            $classArr = implode(',',$data['class_id']);
//            $list = $list->whereIn('a.class_id', $classArr);
//        }
//        // 任务id搜索
//        if (isset($data['task_id']) && !empty($data['task_id'])){
//            $list = $list->where('a.Id', $params['task_id']);
//        }
//
//        //create_time 创建时间
//        if (!empty($data['create_time'])) {
//            $state_time = $data['create_time'][0] . ' 00:00:00';
//            $end_time = $data['create_time'][1] . ' 23:59:59';
//            $list = $list->where('a.create_time', '>=', $state_time)
//                ->where('a.create_time', '<=', $end_time);
//        }
//
//        if (isset($data['is_payment'])){
//            $billMdl = db::table('financial_bill')
//                ->where('a.is_payment', $data['is_payment'])
//                ->get();
//            $billNo = [];
//            if ($billMdl->isNotEmpty()){
//                $billNo = array_unique(array_column($billMdl->toArrayList(), 'bill_no'));
//            }
//            if (empty($billNo)){
//                return ['total' => 0, 'list' => []];
//            }else{
//                $list = $list->where(function($q) use ($billNo){
//                    foreach ($billNo as $no){
//                        $q->orWhere('a.ext', 'like', '%'.$no.'%');
//                    }
//                    return $q;
//                });
//            }
//        }
//
//        $count = $list->count();
//        $list = $list->get();
//        $auditNum = 0; // 待审核
//        $refusedNum = 0; // 已拒绝
//        $ongoingNum = 0; // 进行中
//        $acceptedNum = 0; // 待验收的
//        $endedNum = 0; // 已结束
//        $abnormalEndNum = 0; // 异常结束
//        foreach ($list as $v){
//            if ($v->state == 1){
//                $auditNum += 1;
//                continue;
//            }
//            if ($v->state == 2){
//                $refusedNum += 1;
//                continue;
//            }
//            if ($v->state == 3){
//                $ongoingNum += 1;
//                continue;
//            }
//            if ($v->state == 4){
//                $acceptedNum += 1;
//                continue;
//            }
//            if ($v->state == 5){
//                $endedNum += 1;
//                continue;
//            }
//            if ($v->state == 6){
//                $abnormalEndNum += 1;
//                continue;
//            }
//        }
//
//        $data = [
//            'count' => $count,
//            'audit_num' => $auditNum,
//            'refused_num' => $refusedNum,
//            'ongoing_num' => $ongoingNum,
//            'accepted_num' => $acceptedNum,
//            'ended_num' => $endedNum,
//            'abnormal_end_num' => $abnormalEndNum,
//        ];
//
//        return ['code' => 200, 'msg' => '获取成功！', 'data' => $data];
//    }

    public function task_list_statistics($data)
    {
        $where = "1=1";
        //list_all 所有数据
        if (!$data['list_all']) {
            if ($data['type'] == '1') {
                // 任务
                $where .= " and (t.`user_fz`={$data['user_info']['Id']} or t.`user_cj`={$data['user_info']['Id']})";
            } else if ($data['type'] == '2') {
                // 任务模板
                $where .= " and t.`user_cj`={$data['user_info']['Id']}";
            }
        }
        // 过滤已删除的数据
        $where .= " and t.`is_deleted` = 0";

        //name 任务名称
        if (isset($data['name'])) {
            $where .= " and t.`name` like '%{$data['name']}%'";
        }
        //user_fz_name 负责人名称
        if (isset($data['user_fz_name'])) {
            $where .= " and u_fz.`account` like '%{$data['user_fz_name']}%'";
        }
        //task_keys 任务关键字
        if (isset($data['task_keys'])) {
            $where .= " and t.`ext` like '%{$data['task_keys']}%'";
        }
        //user_cj_name 创建人名称
        if (isset($data['user_cj_name'])) {
            $where .= " and u_cj.`account` like '%{$data['user_cj_name']}%'";
        }
        //state 状态：1.待审核、2.已拒绝、3.进行中、4.待验收、5.已结束
        if (isset($data['state'])) {
            $where .= " and t.`state`={$data['state']}";
        }
        //type 类型：1.任务、2.任务模板
        if (isset($data['type'])) {
            $where .= " and t.`type`={$data['type']}";
        }
        //type_mb 模板类型：1.财务模板、2.人事模板、3.产品开发
        if (!empty($data['type_mb'])) {
            $where .= " and t.`type_mb`={$data['type_mb']}";
        }
        //class_id 任务分类
        if (isset($data['class_id'])) {
            $classArr = implode(',',$data['class_id']);
            $where .= " and t.`class_id` in ($classArr)";
        }
        // 任务id搜索
        if (isset($data['task_id']) && !empty($data['task_id'])){
            $where .= " and t.`Id`={$data['task_id']}";
        }

        //create_time 创建时间
        if (!empty($data['create_time'])) {
            $state_time = $data['create_time'][0] . ' 00:00:00';
            $end_time = $data['create_time'][1] . ' 23:59:59';
            $where .= " and t.create_time>='{$state_time}' and t.create_time<='{$end_time}'";
        }

        if (isset($data['is_payment'])){
            $billMdl = db::table('financial_bill')
                ->where('is_payment', $data['is_payment'])
                ->get();
            $billNo = [];
            if ($billMdl->isNotEmpty()){
                $billNo = array_unique(array_column($billMdl->toArrayList(), 'bill_no'));
            }
            if (empty($billNo)){
                return ['total' => 0, 'list' => []];
            }else{
                $i = 0;
                $len = count($billNo);
                foreach ($billNo as $k => $v){
                    if ($i == 0){
                        $where .= " and (t.ext like '%".$v."%'";
                    }else{
                        $where .= " or t.ext like '%".$v."%'";
                    }
                    $i += 1;
                    if ($i== $len){
                        $where .= ')';
                    }
                }
            }
        }

        if (isset($data['supplier_name'])){
            $supplierMdl = db::table('suppliers')
                ->where('name', 'like', '%'.$data['supplier_name'].'%')
                ->get(['Id']);
            if ($supplierMdl->isEmpty()){
                return ['total' => 0, 'list' => []];
            }
            $supplierIds = array_column($supplierMdl->toArrayList(), 'Id');
            $billMdl = db::table('financial_bill')
                ->whereIn('supplier_id', $supplierIds)
                ->get(['bill_no']);
            $whereNo = [];
            if ($billMdl->isNotEmpty()){
                $whereNo = array_column($billMdl->toArrayList(), 'bill_no');
            }
            $contractMdl = db::table('cloudhouse_contract_total')
                ->whereIn('supplier_id', $supplierIds)
                ->get(['contract_no']);
            if ($contractMdl->isNotEmpty()){
                $whereNo = array_merge($whereNo, array_column($contractMdl->toArrayList(), 'contract_no'));
            }
            if (empty($whereNo)){
                return ['total' => 0, 'list' => []];
            }else{
                $i = 0;
                $len = count($whereNo);
                foreach ($whereNo as $k => $v){
                    if ($i == 0){
                        $where .= " and (t.ext like '%".$v."%'";
                    }else{
                        $where .= " or t.ext like '%".$v."%'";
                    }
                    $i += 1;
                    if ($i== $len){
                        $where .= ')';
                    }
                }
            }
        }

        // 创建时间动态排序
        $order_by = ' DESC ';
        if (isset($data['order_by']) && !empty($data['order_by'])){
            $order_by = ' ASC ';
        }

        //分页
        $limit = "";
//        if ((!empty($data['page'])) and (!empty($data['page_count']))) {
//            $limit = " limit " . ($data['page'] - 1) * $data['page_count'] . ",{$data['page_count']}";
//        }

        $sql = "select SQL_CALC_FOUND_ROWS t.*,u_fz.account as account_fz, u_cj.account as account_cj
				       from tasks t
				       inner join users u_cj on u_cj.Id = t.user_cj
                       left join users u_fz on u_fz.Id = t.user_fz
				       where {$where}
				       order by t.state asc,t.create_time {$order_by} {$limit}";
        // echo $sql;
        $list = json_decode(json_encode(db::select($sql)), true);


        //// 总条数
        if (isset($data['page']) and isset($data['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }

        $auditNum = 0; // 待审核
        $refusedNum = 0; // 已拒绝
        $ongoingNum = 0; // 进行中
        $acceptedNum = 0; // 待验收的
        $endedNum = 0; // 已结束
        $abnormalEndNum = 0; // 异常结束
        foreach ($list as $v){
            if ($v['state'] == 1){
                $auditNum += 1;
                continue;
            }
            if ($v['state'] == 2){
                $refusedNum += 1;
                continue;
            }
            if ($v['state'] == 3){
                $ongoingNum += 1;
                continue;
            }
            if ($v['state'] == 4){
                $acceptedNum += 1;
                continue;
            }
            if ($v['state'] == 5){
                $endedNum += 1;
                continue;
            }
            if ($v['state'] == 6){
                $abnormalEndNum += 1;
                continue;
            }
        }

        $data = [
            'count' => $total[0]->total,
            'audit_num' => $auditNum,
            'refused_num' => $refusedNum,
            'ongoing_num' => $ongoingNum,
            'accepted_num' => $acceptedNum,
            'ended_num' => $endedNum,
            'abnormal_end_num' => $abnormalEndNum,
        ];

        return ['code' => 200, 'msg' => '获取成功！', 'data' => $data];
    }

    public function task_audit_list_statistics($data)
    {
        $where = "t.type=1 and t.state not in (2,4,5)";
        // 过滤已删除的数据
        $where .= " and t.`is_deleted` = 0";
//        $day = date("l");
//        if($day!='Wednesday'){
//            $where .=" and t.class_id!=19";
//        }
        //name 任务名称
        if (isset($data['name'])) {
            $where .= " and t.`name` like '%{$data['name']}%'";
        }
        //user_fz_name 负责人名称
        if (isset($data['user_fz_name'])) {
            $where .= " and u_fz.`account` like '%{$data['user_fz_name']}%'";
        }
        //user_cj_name 创建人名称
        if (isset($data['user_cj_name'])) {
            $where .= " and u_cj.`account` like '%{$data['user_cj_name']}%'";
        }
        //task_keys 任务关键字
        if (isset($data['task_keys'])) {
            $where .= " and t.`ext` like '%{$data['task_keys']}%'";
        }
        if (isset($data['examine_state'])) {
            $examine_state = implode(",", $data['examine_state']);
            $where .= " and te.`state` in ($examine_state)";
        }
        //class_id 任务分类
        if (isset($data['class_id'])) {
            $classArr = implode(',',$data['class_id']);
            $where .= " and t.`class_id` in ($classArr)";
        }
        if (isset($data['task_id'])) {
            $where .= " and t.`Id`={$data['task_id']}";
        }

        if (isset($data['supplier_name'])){
            $supplierMdl = db::table('suppliers')
                ->where('name', 'like', '%'.$data['supplier_name'].'%')
                ->get(['Id']);
            if ($supplierMdl->isEmpty()){
                return ['total' => 0, 'list' => []];
            }
            $supplierIds = array_column($supplierMdl->toArrayList(), 'Id');
            $billMdl = db::table('financial_bill')
                ->whereIn('supplier_id', $supplierIds)
                ->get(['bill_no']);
            $whereNo = [];
            if ($billMdl->isNotEmpty()){
                $whereNo = array_column($billMdl->toArrayList(), 'bill_no');
            }
            $contractMdl = db::table('cloudhouse_contract_total')
                ->whereIn('supplier_id', $supplierIds)
                ->get(['contract_no']);
            if ($contractMdl->isNotEmpty()){
                $whereNo = array_merge($whereNo, array_column($contractMdl->toArrayList(), 'contract_no'));
            }
            if (empty($whereNo)){
                return ['total' => 0, 'list' => []];
            }else{
                $i = 0;
                $len = count($whereNo);
                foreach ($whereNo as $k => $v){
                    if ($i == 0){
                        $where .= " and (t.ext like '%".$v."%'";
                    }else{
                        $where .= " or t.ext like '%".$v."%'";
                    }
                    $i += 1;
                    if ($i== $len){
                        $where .= ')';
                    }
                }
            }
        }

        //create_time 创建时间
        if (!empty($data['create_time'])) {
            $state_time = $data['create_time'][0] . ' 00:00:00';
            $end_time = $data['create_time'][1] . ' 23:59:59';
            $where .= " and t.create_time>='{$state_time}' and t.create_time<='{$end_time}'";
        }

        //分页
        $limit = "";

        $sql = "select SQL_CALC_FOUND_ROWS t.*,u_fz.account as account_fz, u_cj.account as account_cj ,te.state as examine_state
				       from tasks t
				       inner join users u_fz on u_fz.Id = t.user_fz
				       inner join users u_cj on u_cj.Id = t.user_cj
				       inner join tasks_examine te on te.task_id=t.Id and te.is_examine=2 and te.user_id={$data['user_info']['Id']}
				       where {$where}
				       order by t.create_time asc {$limit}";
        $list = json_decode(json_encode(db::select($sql)), true);

        //// 总条数
        if (isset($data['page']) and isset($data['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }
        $auditNum = 0; // 待审核
        $readedNum = 0; // 已阅
        $agreedNum = 0; // 已同意
        $refusedNum = 0; // 已拒绝的
        foreach ($list as $v){
            if ($v['examine_state'] == 1){
                $auditNum += 1;
                continue;
            }
            if ($v['examine_state'] == 2){
                $readedNum += 1;
                continue;
            }
            if ($v['examine_state'] == 3){
                $agreedNum += 1;
                continue;
            }
            if ($v['examine_state'] == 4){
                $refusedNum += 1;
                continue;
            }
        }

        $data = [
            'count' => $total[0]->total,
            'audit_num' => $auditNum,
            'readed_num' => $readedNum,
            'agreed_num' => $agreedNum,
            'refused_num' => $refusedNum,
        ];

        return ['code' => 200, 'msg' => '获取成功！', 'data' => $data];
    }

    public function task_reviewed_list_statistics($data)
    {
        $where = "t.type = 1 and te.state in(3,4)";
        // 过滤已删除的数据
        $where .= " and t.`is_deleted` = 0";
        //name 任务名称
        if (isset($data['name'])) {
            $where .= " and t.`name` like '%{$data['name']}%'";
        }
        //user_fz_name 负责人名称
        if (isset($data['user_fz_name'])) {
            $where .= " and u_fz.`account` like '%{$data['user_fz_name']}%'";
        }
        //user_cj_name 创建人名称
        if (isset($data['user_cj_name'])) {
            $where .= " and u_cj.`account` like '%{$data['user_cj_name']}%'";
        }
        //class_id 任务分类
        if (isset($data['class_id'])) {
            $classArr = implode(',',$data['class_id']);
            $where .= " and t.`class_id` in ($classArr)";
        }
        //task_keys 任务关键字
        if (isset($data['task_keys'])) {
            $where .= " and t.`ext` like '%{$data['task_keys']}%'";
        }
        //state 状态：1.待审核、2.已拒绝、3.进行中、4.待验收、5.已结束
        if (isset($data['state'])) {
            $where .= " and t.`state`={$data['state']}";
        }
        //create_time 创建时间
        if (!empty($data['create_time'])) {
            $state_time = $data['create_time'][0] . ' 00:00:00';
            $end_time = $data['create_time'][1] . ' 23:59:59';
            $where .= " and t.create_time>='{$state_time}' and t.create_time<='{$end_time}'";
        }
        if (isset($data['task_id'])) {
            $where .= " and t.`Id`={$data['task_id']}";
        }

        if (isset($data['supplier_name'])){
            $supplierMdl = db::table('suppliers')
                ->where('name', 'like', '%'.$data['supplier_name'].'%')
                ->get(['Id']);
            if ($supplierMdl->isEmpty()){
                return ['total' => 0, 'list' => []];
            }
            $supplierIds = array_column($supplierMdl->toArrayList(), 'Id');
            $billMdl = db::table('financial_bill')
                ->whereIn('supplier_id', $supplierIds)
                ->get(['bill_no']);
            $whereNo = [];
            if ($billMdl->isNotEmpty()){
                $whereNo = array_column($billMdl->toArrayList(), 'bill_no');
            }
            $contractMdl = db::table('cloudhouse_contract_total')
                ->whereIn('supplier_id', $supplierIds)
                ->get(['contract_no']);
            if ($contractMdl->isNotEmpty()){
                $whereNo = array_merge($whereNo, array_column($contractMdl->toArrayList(), 'contract_no'));
            }
            if (empty($whereNo)){
                return ['total' => 0, 'list' => []];
            }else{
                $i = 0;
                $len = count($whereNo);
                foreach ($whereNo as $k => $v){
                    if ($i == 0){
                        $where .= " and (t.ext like '%".$v."%'";
                    }else{
                        $where .= " or t.ext like '%".$v."%'";
                    }
                    $i += 1;
                    if ($i== $len){
                        $where .= ')';
                    }
                }
            }
        }

        //分页
        $limit = "";
        if ((!empty($data['page'])) and (!empty($data['page_count']))) {
            $limit = " limit " . ($data['page'] - 1) * $data['page_count'] . ",{$data['page_count']}";
        }

        $sql = "select SQL_CALC_FOUND_ROWS t.*, u_fz.account as account_fz, u_cj.account as account_cj
				       from tasks t
				       inner join users u_fz on u_fz.Id = t.user_fz
				       inner join users u_cj on u_cj.Id = t.user_cj
				       inner join tasks_examine te on te.task_id=t.Id  and te.user_id={$data['user_info']['Id']}
				       where {$where}
				       order by te.time_sh desc {$limit}";
        // echo $sql;
        $list = json_decode(json_encode(db::select($sql)), true);

        //// 总条数
        if (isset($data['page']) and isset($data['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }

        $auditNum = 0; // 待审核
        $refusedNum = 0; // 已拒绝
        $ongoingNum = 0; // 进行中
        $acceptedNum = 0; // 待验收的
        $endedNum = 0; // 已结束
        $abnormalEndNum = 0; // 异常结束
        foreach ($list as $v){
            if ($v['state'] == 1){
                $auditNum += 1;
                continue;
            }
            if ($v['state'] == 2){
                $refusedNum += 1;
                continue;
            }
            if ($v['state'] == 3){
                $ongoingNum += 1;
                continue;
            }
            if ($v['state'] == 4){
                $acceptedNum += 1;
                continue;
            }
            if ($v['state'] == 5){
                $endedNum += 1;
                continue;
            }
            if ($v['state'] == 6){
                $abnormalEndNum += 1;
                continue;
            }
        }

        $data = [
            'count' => $total[0]->total,
            'audit_num' => $auditNum,
            'refused_num' => $refusedNum,
            'ongoing_num' => $ongoingNum,
            'accepted_num' => $acceptedNum,
            'ended_num' => $endedNum,
            'abnormal_end_num' => $abnormalEndNum,
        ];

        return ['code' => 200, 'msg' => '获取成功！', 'data' => $data];
    }

    public function get_superiors($params){
        $adduser = $params['user_id'];
        $organizes_member = DB::table('organizes_member')->where('user_id',$adduser)->first();
        if(empty($organizes_member)){
            return ['code' => 500, 'msg' => '您未绑定组织，请联系管理员绑定！', 'data' => ''];
        }
        $superiors = [];
        $memberlist = DB::table('organizes_member')->where('organize_id',$organizes_member->organize_id)->whereIn('type',[1,2,4])->get()->toArray();
        if(empty($memberlist)){
            $organizes = DB::table('organizes')->where('Id',$organizes_member->organize_id)->select('pid')->first();
            if(empty($organizes)){
                return ['code' => 500, 'msg' => '您所在的组织没有负责人或组长！', 'data' => ''];
            }else{
                $memberlist2 = DB::table('organizes_member')->where('organize_id',$organizes->pid)->whereIn('type',[1,2,4])->get()->toArray();
                if(empty($memberlist2)){
                    $organizes2 = DB::table('organizes')->where('Id',$organizes->pid)->select('pid')->first();
                    if(empty($organizes2)){
                        return ['code' => 500, 'msg' => '您所在的组织没有负责人或组长！', 'data' => ''];
                    }else{
                        $memberlist3 = DB::table('organizes_member')->where('organize_id',$organizes->pid)->whereIn('type',[1,2,4])->get()->toArray();
                        if(empty($memberlist2)){
                            return ['code' => 500, 'msg' => '您所在的组织没有负责人或组长！', 'data' => ''];
                        }else{
                            foreach ($memberlist3 as $v3){
                                if(!in_array($v3->user_id,$superiors)){
                                    $superiors[] = $v3->user_id;
                                }
                            }
                        }
                    }
                }else{
                    foreach ($memberlist2 as $v2){
                        if(!in_array($v2->user_id,$superiors)){
                            $superiors[] = $v2->user_id;
                        }
                    }
                }
            }
        }else{
            foreach ($memberlist as $v){
                if(!in_array($v->user_id,$superiors)){
                    $superiors[] = $v->user_id;
                }
            }
        }

        return ['code' => 200, 'msg' => '上级获取成功', 'data' => $superiors];
    }

    public function getTaskDetailList($params)
    {
        $list = db::table('tasks_son as a')
            ->leftJoin('organizes_member as b', 'a.user_id', '=', 'b.user_id')
            ->leftJoin('users as c','a.user_id','=','c.Id')
            ->leftJoin('tasks as d','a.task_id', '=', 'd.Id')
            ->where('d.type', 1);
        $data = db::table('tasks_son as a')
            ->leftJoin('organizes_member as b', 'a.user_id', '=', 'b.user_id')
            ->leftJoin('users as c','a.user_id','=','c.Id')
            ->leftJoin('tasks as d','a.task_id', '=', 'd.Id')
            ->where('d.type', 1);
        if (isset($params['organize_id'])){
            $organizeIds[] = $params['organize_id'];
            $organizeMdl = db::table('organizes')
                ->whereIn('fid', $organizeIds)
                ->where('state', 1)
                ->get()
                ->toArray();
            $organizeIds = array_merge($organizeIds, array_column($organizeMdl, 'Id'));
            $organizeMdl = db::table('organizes')
                ->whereIn('fid', $organizeIds)
                ->where('state', 1)
                ->get()
                ->toArray();
            $organizeIds = array_merge($organizeIds, array_column($organizeMdl, 'Id'));
            $list = $list->whereIn('b.organize_id', $organizeIds);
            $data = $data->whereIn('b.organize_id', $organizeIds);
        }

        if (isset($params['user_id'])){
            $list = $list->where('a.user_id', $params['user_id']);
            $data = $data->where('a.user_id', $params['user_id']);
        }

        if (isset($params['create_time']) && is_array($params['create_time'])){
            $taskMdl = db::table('tasks')
                ->whereBetween('create_time', $params['create_time'])
                ->get()
                ->toArrayList();
            $taskIds = array_column($taskMdl, 'Id');
            $list = $list->whereIn('a.task_id', $taskIds);
            $data = $data->whereIn('a.task_id', $taskIds);
        }

        if (isset($params['status']) && is_array($params['status'])){
            $taskMdl = db::table('tasks')
                ->whereIn('status', $params['status'])
                ->get()
                ->toArrayList();
            $taskIds = array_column($taskMdl, 'Id');
            $list = $list->whereIn('a.task_id', $taskIds);
            $data = $data->whereIn('a.task_id', $taskIds);
        }

        if (isset($params['state'])){
            $list = $list->where('a.state', $params['state']);
            $data = $data->where('a.state', $params['state']);
        }

        if (isset($params['class_id']) && is_array($params['class_id'])){
            $taskMdl = db::table('tasks')
                ->whereIn('class_id', $params['class_id'])
                ->get()
                ->toArrayList();
            $taskIds = array_column($taskMdl, 'Id');
            $list = $list->whereIn('a.task_id', $taskIds);
            $data = $data->whereIn('a.task_id', $taskIds);
        }

        $count = $list->count();

        if (isset($params['limit']) || isset($params['page'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $list = $list->limit($limit)
                ->offset($offsetNum);
        }

        $list = $list->where('c.state',1)
            ->orderBy('a.create_time', 'desc')
            ->orderBy('a.user_id', 'asc')
            ->get(['a.*', 'b.organize_id']);
        $data = $data->where('c.state',1)
            ->orderBy('a.create_time', 'desc')
            ->orderBy('a.user_id', 'asc')
            ->get(['a.*', 'b.organize_id']);

        $organizeMdl = db::table('organizes')
            ->get();
        $organizeList = [];
        foreach ($organizeMdl as $o){
            $organizeList[$o->Id] = $o->name;
        }

        $userMdl = db::table('users')
            ->get();
        $userList = [];
        foreach($userMdl as $u) {
            $userList[$u->Id] = $u->account;
        }
        $taskNewMdl = db::table('tasks_news')
            ->get();
        $taskNewList = [];
        foreach ($taskNewMdl as $n){
            $n->user_fs_name = $userList[$n->user_fs] ?? '';
            $n->user_js_name = $userList[$n->user_js] ?? '';
            $n->file = json_decode($n->file, true);
            $n->img = json_decode($n->img, true);
            $taskNewList[$n->task_id][] = $n;
        }
        $taskSonScoreMdl = db::table('tasks_son_score')
            ->get();
        $taskSonScoreList = [];
        foreach ($taskSonScoreMdl as $s){
            $s->user_name = $userList[$s->user_id] ?? '';
            $taskSonScoreList[$s->task_son_id] = $s;
        }

        $taskMdl = db::table('tasks')
            ->where('is_deleted', 0)
            ->get();
        $taskList = [];
        foreach ($taskMdl as $t){
            $taskList[$t->Id] = $t;
        }
        foreach ($list as $v) {
            $v->day_yj = $v->day_yj . '天';
            $v->organize_name = $organizeList[$v->organize_id] ?? '未绑定组织架构';
            $v->task_new = $taskNewList[$v->task_id] ?? [];
            $v->user_name = $userList[$v->user_id] ?? '';
            $v->task_son_score = $taskSonScoreList[$v->Id] ?? [];
            $v->feedback_content2 = json_decode($v->feedback_content2, true);
            $v->task_name = $taskList[$v->task_id]->name ?? '';
            $v->status_name = Constant::TASKS_SON_STATUS[$v->state] ?? '';
            $v->sj_day = '任务未完成';
            if ($v->state == 3){
                if ($v->time_end_sj == '0000-00-00 00:00:00'){
                    $v->sj_day = '任务实际完成时间未记录';
                    continue;
                }
                if ($v->time_state == '0000-00-00 00:00:00'){
                    $v->sj_day = '任务开始时间未记录';
                    continue;
                }
                $time = (strtotime($v->time_end_sj) - strtotime($v->time_state)) / (60*60);
                $v->sj_day = round($time, 2).'小时';
            }
        }

        $auditNum = 0; // 未开始
        $readedNum = 0; // 进行中
        $agreedNum = 0; // 已完成
        $refusedNum = 0; // 已放弃
        $timedNum = 0; // 已逾期
        foreach ($data as $v){
            if ($v->state == 1){
                $auditNum += 1;
                continue;
            }
            if ($v->state == 2){
                $readedNum += 1;
                $now = date('Y-m-d H:i:s', microtime(true));
                if ($now > $v->time_end_yj){
                    $timedNum += 1;
                }
                continue;
            }
            if ($v->state == 3){
                $agreedNum += 1;
                if ($v->time_end_sj > $v->time_end_yj){
                    $timedNum += 1;
                }
                continue;
            }
            if ($v->state == 4){
                $refusedNum += 1;
                continue;
            }
        }

        $result = [
            'count' => $count,
            'audit_num' => $auditNum,
            'readed_num' => $readedNum,
            'agreed_num' => $agreedNum,
            'refused_num' => $refusedNum,
            'timed_num' => $timedNum
        ];

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list, 'result' => $result]];
    }
}//结束符
